Tuesday, 31 March 2015

JavasScript Remoting using VisualForce and Apex (SalesForce)

Remoting allows us to perform almost any apex logic via Javascript.

Let's consider Javascript remoting as similar as AJAX call done in normal websites built using PHP, ASP.NET or so.

So, let's see how we can do this.

In this demo, I have attempted to create a drop-down list having
options created dynamically based on the data from a custom object
and then calling a javascript function(at onchange event) which
refers to a remote action of the controller positionController written in apex.


The VisualForce Page Contains the code as below

<apex:page controller="poistionController" showHeader="false">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
//Function that calls the controller written in Apex and returns the required data.

function selectPosition(id){
 
var pos = document.getElementById(id).value;

    poistionController.getPositionDetails( pos,

    function(result, event){

         if (event.status && event.result) {

         // Creating the HTML content based on

         //the data returned from positionController and getPositionDetails method.

              var html = '<table>';

           html = html + '<tr><td>Position Name :</td>';

            html = html + '<td>'+event.result[0].Name+'</td></tr>';

            html = html + '<tr><td>Min Pay :</td>';

            html = html + '<td>'+'$'+event.result[0].Min_Pay__c+'</td></tr>';

            html = html + '<tr><td>Max Pay :</td>';

            html = html + '<td>'+'$'+event.result[0].Max_Pay__c+'</td></tr>';

            html = html + '</table>';

            $('#positionDetails').html(html);

      } else {

             alert(event.message);

      }

}, {escape:true});

}

 </script>

   <div align="center" width="550px">

      <h1>Congratulations</h1>

      This is my new Page : <b>VisualForce & Apex !!!</b><br />
  <apex:outputText value="Your maximum salary could be AT MAXIMUM {!pos.Max_Pay__c}"/>

      </b>

      <apex:form >

        <apex:selectList value="{!pos}" multiselect="false" size="1" id="positionTitle" onchange="selectPosition('{!$component.positionTitle}');">

         <apex:selectOptions value="{!options}"/>

         </apex:selectList>

      </apex:form>

   </div>

   <div id="positionDetails" align="center">

         <!-- Position details is displayed here. -->

   </div>

</apex:page>

 positionController contains codes as below.

global with sharing class poistionController {

      public Position__c pos{get;set;}
      public List<Position__c> title{get;set;}
      public List<Position__c> positions{get;set;}

      public poistionController() {

         pos = [select Max_Pay__c from Position__c where Name = 'Sr. Java Developer'];
      }
       /**

      * Method that creates the select option dynamically.

      **/

      public List<SelectOption> getOptions() {

          List<SelectOption> options = new List<SelectOption>();
          title = [select Position__c.Name from Position__c];
         //Creating an NULL option.
         options.add(new SelectOption('none','--Select--'));
         for( Position__c a :title ){

            options.add(new SelectOption(a.Name,a.Name));
         }
         return options;
      }

      /**

      * Remote action involved with Javascript remoting and is made global

      **/

      @RemoteAction
      global static Position__c[] getPositionDetails(String pos) {
          return [select Position__c.Name, Max_Pay__c, Min_Pay__c, Days_Open__c from Position__c WHERE                         Position__c.Name =: pos];

      }

}

In the above code for positionController, method named getOptions() is involved with creating options for drop-down list and getPositionDetails() is involved with fetching position details and acts as the remote action and is made global.

In the VisualForce page the javascript method selectPosition() refers to the remote action getPositionDetails() of positionController.

The portion of selectPosition() method in grey and italics is used for javascript remoting.

escape specifies whether the response from the Apex method will be escaped or not.

By default it's TRUE.

The syntax for javascript remoting is as given below,

[<namespace>.]<controller>.<method>([params...,] <callbackFunction>(result, event) {

     // callback function logic

}, {escape:true});

Here, namespace is optional and is required if the class comes from an installed package.

In the controller, the Apex method declaration must be preceded with @RemoteAction annotation as shown below.

@RemoteAction

global static String methodName(String objectName) {

   //Logic written in Apex.

}

The methods with @RemoteAction annotation must be global and static.

The response from the server is in JSON format.

For this demo, it's something like as given below.

[{"type":"rpc","tid":3,"action":"poistionController",

"method":"getPositionDetails","result":{"serId":1,

"value":[{"serId":2, "value":{"Days_Open__c":142,"Name":"Sr. PHP Developer",

"Max_Pay__c":2500000.00,"Id":"a0190000002RNUJAA4", "Min_Pay__c":1500000.00}}]}}]

12 comments: