Ajax-Salesforce Complete Material
Ajax-Salesforce Complete Material
Ajax-Salesforce Complete Material
Salesforce offer AJAX tool kit to run javascript and allowing user to make a
connection with Salesforce and query salesforce from javascript, the data inreturn can be handled in own fashion to be displayed on the page
Note : Ajax tool kit should be used when you want to work with records upto
200 with 5 to 6 fields in the object
The following are examples of scenarios that require case-by-case analysis:
Update more than 200 records.
Update records that are unusually large. For example, what happens if
the user clicks the browser stop button?
Recalculate a complex value for more than 200 records.
Step 1: include
to Connection.SessionID
1.sforce.connection.sessionId = "{!$Api.Session_ID}";
Or
2.We can login using username and password
Var result =Sforce.connection.login(username,password+resettoken);
sforce.connection.sessionId=result.sessionId;
step 3 :Write a query :
string str='select id,name from Account';
step 4: Execute the Query
var queryResult = sforce.connection.query(str);
Step 5: Check wheather the queryResult has element ;
if(queryResult.size >0)
Step 6: Get all the records into an array
var records = queryResult.getArray('records');
==============================
Reference Codes:
//-- Ajax Query: sync
result = sforce.connection.query("Select Name,Id from User");
records = result.getArray("records");
for (var i=0; i<records.length; i++) {
var record = records[i];
log(record.Name + " -- " + record.Id);
}
============================================================================
//-- Ajax Query: async
var result = sforce.connection.query("Select Name,Id from User", {
onSuccess : success,
onFailure : failure
});
function success(result) {
var records = result.getArray("records");
function failure(error) {
log("oops something went wrong " + error);
}
=============================================================================
//-- Ajax Query: async inline function
var result = sforce.connection.query("Select Name,Id from User", {
onSuccess : function(result) {
var records = result.getArray("records");
for (var i=0; i<records.length; i++) {
var record = records[i];
log(record.Name + " -- " + record.Id);
}
},
onFailure : function(error) {
log("oops something went wrong " + error);
}
});
=============================================================================
//-- Ajax Query: query result iterator
var result = sforce.connection.query("Select Name,Id from User", {
onSuccess : success, onFailure : failure});
function success(result) {
var it = new sforce.QueryResultIterator(result);
while(it.hasNext()){
var record = it.next();
log(record.Name + " -- " + record.Id);
}
}
function failure(error) {
log("oops something went wrong " + error);
}
============================================================================
//-- Ajax Query: query more sync
var result = sforce.connection.query("select name, id from account");
var queryMore = true;
while (queryMore) {
var records = result.getArray("records");
var sb = new sforce.StringBuffer();
for (var i = 0; i < records.length; i++) {
sb.append(records[i].Name).append(",");
}
log(records.length);
log(sb.toString());
if (result.queryLocator == null) {
queryMore = false;
} else {
result = sforce.connection.queryMore(result.queryLocator);
}
}
==========================================================================
//-- Ajax Query: query more async
sforce.connection.query("Select Name,Id from Account", {
onSuccess : success, onFailure : log });
function success(result) {
var records = result.getArray("records");
var sb = new sforce.StringBuffer();
for (var i=0; i<records.length; i++) {
var record = records[i];
sb.append(record.Name).append(",");
}
log(records.length);
log(sb.toString());
if (result.queryLocator) {
sforce.connection.queryMore(result.queryLocator, {
onSuccess : success, onFailure : log});
}
}
=============================================================================
//-- Ajax Query: query all sync
var result = sforce.connection.queryAll("Select Name,Id from User");
var records = result.getArray("records");
for (var i=0; i<records.length; i++) {
var record = records[i];
}
==========================================================================
//-- Ajax Query: joins
var result = sforce.connection.query("select a.name, a.industry, " +
"(select c.lastname, c.leadsource from a.contacts c) " +
"from account a limit 100");
var ait = new sforce.QueryResultIterator(result);
while(ait.hasNext()) {
var account = ait.next();
var contacts = [];
if (account.Contacts) {
var cit = new sforce.QueryResultIterator(account.Contacts);
while(cit.hasNext()) {
var contact = cit.next();
contacts.push(contact.LastName);
}
}
log(account.Name + ": " + contacts.join(","));
}
=============================================================================
//-- Ajax CRUD: create - sync
var account = new sforce.SObject("Account");
account.Name = "my new account";
var result = sforce.connection.create([account]);
if (result[0].getBoolean("success")) {
log("new account created with id " + result[0].id);
} else {
log("failed to create account " + result[0]);
}
============================================================================
//-- Ajax CRUD: create - async
var account = new sforce.SObject("Account");
account.Name = "my new account";
sforce.connection.create([account],
{onSuccess : success, onFailure : failed});
function success(result) {
if (result[0].getBoolean("success")) {
log("new account created with id " + result[0].id);
} else {
log("failed to create account " + result[0]);
}
}
function failed(error) {
log("oops something went wrong " + error);
}
===========================================================================
//-- Ajax CRUD: create- with other data types
var campaign = new sforce.SObject("Campaign");
campaign.Name = "new campaign";
campaign.ActualCost = 12938.23;
campaign.EndDate = new Date();
campaign.IsActive = true;
sforce.connection.create([campaign ],
{onSuccess : success, onFailure : log});
function success(result) {
if (result[0].getBoolean("success")) {
log("new campaign created with id " + result[0].id);
} else {
log("failed to create campaign " + result[0]);
}
}
===========================================================================
} else {
log("merge failed " + result[0]);
}
=============================================================================
//-- Ajax CRUD: undelete
var account = new sforce.SObject("Account");
account.Name = "account to delete";
account.Phone = "2837484894";
result = sforce.connection.create([account]);
account.id = result[0].id;
log("account created " + account);
result = sforce.connection.deleteIds([account.id]);
if (!result[0].getBoolean("success")) throw "delete failed";
log("account deleted " + result);
result = sforce.connection.undelete([account.id]);
if (!result[0].getBoolean("success")) throw "undelete failed";
log("account undeleted " + result[0]);
=========================================================================
//-- Ajax CRUD: retrieve
var account = new sforce.SObject("Account");
account.Name = "retrieve update test";
account.Phone = "2837484894";
var result = sforce.connection.create([account]);
if (result[0].getBoolean("success") == false) throw "create failed";
log("account created " + result[0]);
result = sforce.connection.retrieve("Name,Phone", "Account",
[result[0].id]);
if (result[0] == null) throw "retrive failed";
log("account retrieved: " + result[0]);
result[0].Phone = "111111111111";
result = sforce.connection.update(result);
if (result[0].getBoolean("success") == false) throw "update failed";
log("account updated: " + result[0]);
=============================================================================
//-- Ajax CRUD: retrieve async
var account = new sforce.SObject("Account");
account.Name = "retrieve update test";
account.Phone = "2837484894";
var result = sforce.connection.create([account]);
if (result[0].getBoolean("success") == false) throw "create failed";
log("account created " + result[0]);
var callback = {
onSuccess: function(result) {
if (result[0] == null) throw "retrive failed";
log("account retrieved: " + result[0]);
},
onFailure: function(error) {
log("failed due to " + error);
}
};
result = sforce.connection.retrieve("Name,Phone", "Account",
[result[0].id], callback);
//-- Ajax Describe: SObject
var result = sforce.connection.describeSObject("Account");
log(result.label + " : " + result.name + " : ");
log("---------- fields ---------");
for (var i=0; i<result.fields.length; i++) {
var field = result.fields[i];
log(field.name + " : " + field.label + " : " + field.length + " : ");
}
log("---------- child relationships ---------");
for (var i=0; i<result.childRelationships.length; i++) {
var cr = result.childRelationships[i];
log(cr.field + " : " + cr.childSObject);
}
log("---------- record type info ----------");
for (var i=0; i<result.recordTypeInfos.length; i++) {
var rt = result.recordTypeInfos[i];
log(rt.name);
}
=============================================================================
//-- Ajax Describe: SObjects
var result = sforce.connection.describeSObjects(["Account", "Contact"]);
for (var i=0; i<result.length; i++) {
log(result[i].label + " : " + result[i].name + " : ");
}
//-- Ajax Describe: global
var result = sforce.connection.describeGlobal();
var types = result.getArray("types");
for (var i=0; i<types.length; i++) {
log(types[i]);
}
//-- Ajax Describe: layout
var result = sforce.connection.describeLayout("Account");
var layouts = result.getArray("layouts");
for (var i=0; i<layouts.length; i++) {
var layout = layouts[0];
detailLayoutSections(layout.detailLayoutSections);
}
function detailLayoutSections(sections) {
for (var i=0; i<sections.length; i++) {
var section = sections[i];
log(section.columns + ":" + section.heading + ":");
layoutRows(section.getArray("layoutRows"));
}
}
function layoutRows(rows) {
for (var i=0; i<rows.length; i++) {
var row = rows[i];
layoutItems(row.getArray("layoutItems"));
}
}
function layoutItems(items) {
for (var i=0; i<items.length; i++) {
var item = items[i];
log(" " + item.label);
}
}
=============================================================================
//-- Ajax Describe: tabs
var result = sforce.connection.describeTabs();
for (var i=0; i<result.length; i++) {
var tabSet = result[i];
log( tabSet.label);
displayTabs(tabSet.get("tabs"));
}
function displayTabs(tabs) {
for( var i=0; i<tabs.length; i++) {
var tab = tabs[i];
log( " " + tab.label + " " + tab.url);
}
}
============================================================================
//-- Ajax Util: get deleted
var start = new Date();
var end = new Date();
start.setDate(end.getDate() - 1);
var result = sforce.connection.getDeleted("Account", start, end);
var records = result.getArray("deletedRecords");
log("following records are deleted:");
for (var i=0; i<records.length; i++) {
log(records[i].id);
}
==============================================================================
//-- Ajax Util: get updated
var start = new Date();
var end = new Date();
start.setDate(end.getDate() - 1);
var result = sforce.connection.getUpdated("Account", start, end);
'<mrns0:getRate><country1 xsi:type="xs:string">us</country1>' +
'<country2 xsi:type="xs:string">india</country2> </mrns0:getRate>
</soap:Body> </soap:Envelope>';
sforce.connection.remoteFunction({
url : "http://services.xmethods.net/soap",
requestHeaders: {"Content-Type":"text/xml",
"SOAPAction": "\"\""
},
requestData: envelope,
method: "POST",
onSuccess : function(response) {
log(response);
},
onFailure : function(response) {
log("Failed testRemoteFunctionPostAsync " + response)
}
});
//-- Ajax Remote Proxy: xml mime type
/* This feature is not enabled by default.
Please contact support */
var envelope =
'<soap:Envelope xmlns:mrns0="urn:xmethods-CurrencyExchange" ' +
'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" ' +
'xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" ' +
'xmlns:xs="http://www.w3.org/2001/XMLSchema" ' +
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +
'<soap:Body
soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
'<mrns0:getRate><country1 xsi:type="xs:string">us</country1>' +
'<country2 xsi:type="xs:string">india</country2> </mrns0:getRate>
</soap:Body> </soap:Envelope>';
sforce.connection.remoteFunction({
url : "http://services.xmethods.net/soap",
mimeType: "text/xml",
requestHeaders: {"Content-Type":"text/xml",
"SOAPAction": "\"\""
},
requestData: envelope,
method: "POST",
onSuccess : function(response) {
log("response is " + typeof response);
logXml(response);
},
onFailure : function(response) {
log("Failed testPostMimeType: " + response)
}
});
function logXml(node) {
if (node.nodeValue == null) {
log(node.nodeName);
} else {