Force.com platform provides a JavaScript API which provides features to work with sObjects using JavaScript without the help of Apex codes. Is it always necessary to write an apex class for every visualforce page we build ? Not really. Because we have an well built javascript API available in force.com platform I am sure this is a nicest way to work with salesforce sObjects (Standard / Custom). Let’s highlight some important tips for this. |
Let’s include the library. |
Now let’s see how we can fetch data from the sObjects
var result = sforce.connection.query("SELECT Id, Name FROM Account LIMIT 1"); //Fetching data from Account object using SOQL. var records = result.getArray("records"); // The query result-set is assigned as an array. if( records.length > 0 && records[0].Id != null ){ var accId = records[0].Id; // Assigning to variables var accName = records[0].Name; // Assigning to variables }else{ alert('No records found.'); }
Since, we have the data assigned to different variables, now we can use the data either for displaying or some calculations as per the need using javascript.
Let’s find out how we can insert the data in sObjects
var newRecords = new Array();
var accObj = new sforce.SObject(“Account”); // Creating an instance of the sObject
accObj.Name = ‘Mindfire’; //Assigning the Account Name.
newRecords.push(accObj); //Adding records.
sforce.connection.create(newRecords); //Inserting data into the Account object.
Let’s see how we can update specific records.
var newRecords = new Array(); //Fetching data from Account object using SOQL. var result = sforce.connection.query("SELECT Id, Name FROM Account WHERE Name='Mindfire' LIMIT 1"); var records = result.getArray("records"); // The query result-set is assigned as an array. var accObj = new sforce.SObject("Account"); // Creating an instance of the sObject accObj.set(“Id”, records[0].Id ); //Setting the Id to be updated accObj.Name = 'Mindfire Account'; //Assigning the Account Name. accObj.Descripton = 'Account for Mindfire'; //Assigning the Account Description newRecords.push(accObj); //Adding records. sforce.connection.update(newRecords); //Updating data into the Account object.
While inserting or updating, I have used hard-coded values, instead we can get the form data using javascript and can use them.
We can find more about the Salesforce AJAX TOOLKIT at
http://www.salesforce.com/us/developer/docs/ajax/index_Left.htm#CSHID=sforce_api_ajax_calls.htm
|StartTopic=Content%2Fsforce_api_ajax_calls.htm|SkinName=webhel