вторник, 6 мая 2014 г.

Updating fields in Salesforce without using APEX or Field Updates


Today I’m going to walk through a soultion, that can be used for updating records in Salesforce without using APEX code or Workflow rule and Field update.

For example, we need to count a number of Leads wich were converted to a specific Contact. 

1. Let’s add Number type field on a Contact. 
Go to: Setup | Contacts | Fields | New custom field button. Let's call it: # of converted Leads. In the end it will look this way:


2. This field will be updated using a custom button. So let's create a Contact button called 'Calculate number of Converted Leads'. 
Go to: Setup | Contacts | Buttons, Links, and Actions | New Button or Link

Label: Calculate number of Converted Leads
Name: CalculateNumberOfConvertedLeads
Display Type: Detail Page Button
Behaviour: Execute JavaScript
Content: Source: OnClick  JavaScript




Then we need to add a JavaScript code, which will be executed when the button is pressed. In this code we will need to count number of leads, converted to a contact, and to complete this task we will use AJAX Toolkit.  

Here is a code:

 {!requireScript("/soap/ajax/30.0/connection.js")}  
 var url = parent.location.href;  
 var contact = new sforce.SObject("Contact");  
 contact.Id = '{!Contact.Id}';  
 var result = sforce.connection.query("Select count(Id) numberOfConvertedLeads from Lead where ConvertedContactId = '" + contact.Id +"'", {  
   onSuccess : success, onFailure : failure});  
  function success(result) {  
      //here we will store a number of converted leads  
      var convertedLeads = 0;   
      var it = new sforce.QueryResultIterator(result);  
      // iterating over results  
      while(it.hasNext()){  
         var record = it.next();  
         convertedLeads = record.numberOfConvertedLeads;      
      }  
      //updating Contact record  
      contact.NumberOfConvertedLeads__c = convertedLeads;       
      result = sforce.connection.update([contact]);  
      //refreshing a web page  
      parent.location.href = url;  
  }  
  function failure(error) {  
        alert(error);  
  }