Menu Bar

Wednesday 22 August 2012

Javascript Remoting for APEX controller


Javascript remoting is the process that provides support for some methods in APEX controllers to be called via Javascript.The @RemoteAction annotation is currently available as a Developer preview.You have to contact Salesforce.com support to enable this feature.To use Javascript remoting, your request must take the following form:

  1. [<namespace>.]<controller>.<method>([params...,] <callbackFunction>(result, event)  
  2. {  
  3. // callback function logic  
  4. }, {escape:true});  

  • namespace is your organization's namespace. This is only required if the class comes from an installed packaged.
  • controller is the name of your Apex controller
  • method is the name of the Apex method you're calling
  • params is the comma–separated list of parameters that your method takes
  • callbackFunction is the name of the function that handles the response from the controller. It returns the status of the call and the method result.
  • escape defines whether your response should be escaped (by default, true) or not (false)
In controller, your Apex method declaration is preceded with the @RemoteAction annotation like this:


  1. @RemoteAction  
  2. global static String getItemId(String objectName) { ... }  
Example code:

/*VF page*/


  1. <script type="text/javascript">  
  2. function updateStatus(input,id) {  
  3. var inputStatus=id;  
  4. shortList.doShortListThroughCheck(inputStatus,function(result,event){  
  5. if(input.checked){  
  6.  document.getElementById(id).value="Short Listed";  
  7. alert(document.getElementById(id).value);  
  8. }else{  
  9.  document.getElementById(id).value="New";  
  10.  alert(document.getElementById(id).value);  
  11. }  
  12. },{escape:true});  
  13. }</script>  
/*@VF Component*/

  1. <apex:selectCheckboxes onclick="updateStatus(this,'{!app.Name}');">  
  2.        </apex:selectCheckboxes>  
/*In Controller*/

  1. @RemoteAction  
  2. global static Applicant__c doShortListThroughCheck(String para){  
  3.     Applicant__c applicant;      
  4.     try{  
  5.    applicant=[select Name, Name__c, Status__c from Applicant__c where Name =:para limit 1];  
  6.                  applicant.Status__c='Short Listed';       
  7.            update applicant;     
  8.                   
  9.     }catch(DMLException e){  
  10.          ApexPages.addMessages(e);  
  11.          return null;     
  12.     }          
  13. return null;  

No comments: