Data three ways from Force.com…




Over the past couple of months there has been a lot of chatter about some new ways to access your Salesforce.com data. The REST API was released earlier this year as well as something called JavaScript remoting that is in developer release. I currently use standard Apex and Visualforce when creating custom apps on the platform so I thought I would take some time to better understand the REST API and JavaScript remoting.

I had a fun night playing with the code samples provided by Salesforce and thought I would share some examples. Below are three different ways you could access your data on the platform. My goal was very simple…query Salesforce for a list of accounts and display them in a table. Not earth shattering at all but hopefully the simple use case will illustrate three different approaches. Each approach will output a data table exactly like this:





Recipe 1: Using standard Visualforce page with Apex class

The first approach I took was to use an Apex class to query the data and then use a Visualforce page to display it. This is pretty standard Force.com development and should look familiar.

Here is the Apex class:
public with sharing class dataTableOne {

 public List getAccounts() {
  
  List accountsForPage = [Select Id,Name,Phone From Account Limit 10];
  return accountsForPage;
  
 }
}


Here is the Visualforce page:

 
Data retrieved using standard APEX/Visualforce
Account Name Account Id


Recipe 2: Using JavaScript Remoting

When I first saw Josh Birk (@joshbirk) demo JavaScript Remoting at the Minneapolis user group meeting my reaction was, “That looks a lot like those old s-controls we use to write before APEX/Visualforce”. After he talked me off the ledge I got a better understanding of what situations you might use remoting (mobile dev, no viewstate, etc). I used his blog post here to build my recipe below.

Here is the Apex class:
global class dataTableTwo {

    @RemoteAction
    global static Account[] findAccounts() {
       
        Account[] accountsForPage = [Select Id,Name,Phone From Account Limit 10];
        return accountsForPage;
    }


}

Here is the Visualforce page:


 
 
Data retrieved via JavaScript Remoting

Data retrieved via JavaScript Remoting


Recipe 3: Using the REST API and JavaScript toolkit

The last recipe uses the REST API to access the data from Salesforce and has no APEX class. I leaned heavily on Pat Patterson’s (@metaDaddy) blog post and the JavaScript toolkit he created. Thanks Pat! You can see below that once you include his toolkit as a static resource it is just a few lines of code to query data.


Here is the Visualforce page:


 
    
    
    
    
Data was retrieved via REST API

Hope this was helpful. Love to hear any questions or feedback.

0 comments:

Post a Comment

top