Another thing I commonly find myself doing is using Javascript to query Objects and data inside button click events. Why not create an Apex Controller and a Visual Force Page? Well because sometimes the amount of code you need versus the amount of work you might have to do are quiet drastic, also sometimes you don’t need a page to display any results.

In this example I’m going to create a simple button click event that based on the record type displays a message….you can easily modify this code to perform any type of action you wish, but this simple example should get you started.

First a couple of things. In order to use the SOQL database query engine we must first have access to the Salesforce.com Objects. We get this using the AJAX toolkit. The AJAX toolkit is a series of javascript functions you include on you APEX page or Custom Button. When using them in a custom button you can use the REQUIRESCRIPT notation.

{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")}

In both cases you still need to have a Session Id. A Session Id is a token that connects the code to the proper instance of Salesforce and the Organization against which the code should execute. You can use GETSESSIONID() to retrieve this token.

var __sfdcSessionId = '{!GETSESSIONID()}';

When you are using a call from a Visual Force Page you can reference the Global Variable $API and use the Session_ID value:

var __sfdcSessionId = ‘{!$API.SessionID}’;

So now you have the access it’s just a matter of making a query. Let’s say that we are on an Account and we need access to a value on the Contact record.

{!REQUIRESCRIPT("/soap/ajax/26.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/26.0/apex.js")} 

var sql;
var result;
var it;
var obj;
var name;

try
{   
   sql = "SELECT FirstName, LastName FROM Contact WHERE Account = '” + “{!Account.Id}” + “’”;              

    sforce.connection.sessionId = __sfdcSessionId;  
    result = sforce.connection.query(sql);         
    it = new sforce.QueryResultIterator(result);
       
    while (it.hasNext()) 
    {
        obj = it.next(); 
        name = obj.FirstName + ‘ ‘ + obj.LastName;
    }        
} 
catch(e) 
{
    valid = false;
    alert('Error : ' + e);
}

If(name != NaN)
    alert('Error : ' + e);

 

So there you have it. A template to query any Object in a Custom Button

[contact-form]
Filed under: Salesforce.com Programming