Saturday, December 27, 2014

What is @RemoteAction in Salesforce?

What is @RemoteAction in Salesforce and when we are going to use this @RemoteAction?

JavaScript remoting in Visualforce provides support for some methods in Apex controllers to be called via JavaScript.

JavaScript remoting has three parts:
  •  The remote method invocation you add to the Visualforce page, written in JavaScript.
  • The remote method definition in your Apex controller class. This method definition is written in Apex, but there are few differences from normal action methods.
  • The response handler callback function you add to or include in your Visualforce page, written in JavaScript.
To use JavaScript remoting in a Visualforce page, add the request as a JavaScript invocation with the following form:
[namespace.]controller.method(    [parameters...,]    callbackFunction,    [configuration]);

  • namespace is the namespace of the controller class. This is required if your organization has a namespace defined, or if the class comes from an installed package.
  • controller is the name of your Apex controller.
  •  method is the name of the Apex method you’re calling.
  • parameters is the comma-separated list of parameters that your method takes.
  • callbackFunction is the name of the JavaScript function that will handle the response from the controller. You can also declare an anonymous function inline. callbackFunction receives the status of the method call and the result as parameters.
  • configuration configures the handling of the remote call and response. Use this to specify whether or not to escape the Apex method’s response. The default value is {escape: true}.

Example 1:

Visualforce Page:

<apex:page controller="AccountRemoteActionController">
    <script type="text/javascript">
    function getAccountJS() 
        //get the values of input text and place into the variable.
        var accountNameJS = document.getElementById('accName').value;        
        AccountRemoteActionController.getAccount( accountNameJS, 
        function(result, event)
          alert('event.type === '+event.type);
          alert('event.message ==>'+event.message);
            if (event.status) 
                // demonstrates how to get ID for HTML and Visualforce tags
                document.getElementById("{!$Component.theBlock.thePageBlockSection.theFirstItem.accId}").innerHTML = result.Id;
                document.getElementById("{!$Component.theBlock.thePageBlockSection.theSecondItem.accNam}").innerHTML = result.Name;
            else if (event.type === 'exception') 
                document.getElementById("errors-js").innerHTML = event.message;
            } else 
                document.getElementById("errors-js").innerHTML = 'No Records Found..';
        }, {escape:true});
    Account Name :<input id="accName" type="text" />
    <button onclick="getAccountJS()">Get Account</button>
    <div id="errors-js"> </div>
    <apex:pageBlock id="theBlock">
        <apex:pageBlockSection id="thePageBlockSection" columns="2">
            <apex:pageBlockSectionItem id="theFirstItem">
                <apex:outputText id="accId"/>
            <apex:pageBlockSectionItem id="theSecondItem" >
                <apex:outputText id="accNam" />

Controller Class:

global class AccountRemoteActionController
    public String accountName { get; set; }
    public static Account account { get; set; }
    //Default Constructor..
    public AccountRemoteActionController() {
    global static Account getAccount(String accountName) 
        account = [select id, name, phone, type, numberofemployees from Account where name = :accountName ];
        return account;

Out Put:


Example 2:

In this example once the user selected a particular opportunity stage name then calling the remote method from java script and print the opportunity details in table format.

Visualforce Page :

<apex:page controller="OpportunityRemoteActionController" showHeader="true"> <script type="text/javascript" src=""></script> <script type="text/javascript"> function getStageJS(){ var oppStage= document.getElementById("{!$Component.theFm.oppStage}").value; alert("stageName==>"+oppStage); OpportunityRemoteActionController.getOpportunityDetails( oppStage, function(result, event){ // alert("event.status==>"+event.status); // alert("event.result==>"+event.result); var html = '<table border="thick solid">'; html = html + '<caption><b>Opportunity Details</b></caption><tr></tr>'; html = html + '<tr><th>Opportunity Name</th>'; html = html + '<th>Amount</th> </tr>'; if (event.status && event.result) { debugger; // alert("event.result[0].Name==>"+event.result[0].Name); for (var prop in event.result) { // important check that this is objects own property not from prototype prop inherited //alert(prop + " = " + event.result[prop].Name); html = html + '<tr><td><a href="'+event.result[prop].Name+'</td> <td>'+event.result[prop].Amount+'</td></tr> '; } html = html + '</table>'; // alert("html==>"+html); $("#opportunityDetails").html(html); } else { alert(event.message); } }, {escape:true}); } </script> <div align="center" width="550px"> <apex:form id="theFm"> <apex:selectList value="{!stageName}" size="1" id="oppStage" onchange="getStageJS()"> <apex:selectOptions value="{!options}"/> </apex:selectList> </apex:form> </div> <br/> <br/> <div id="opportunityDetails" align="center"> <!-- Opportunity details is displayed here. --> </div> </apex:page>

Controller Class:

global with sharing class OpportunityRemoteActionController { public Opportunity opp{get;set;} public String stageName{get;set;} public OpportunityRemoteActionController() { } /** * Method that creates the select option dynamically. **/ public List<SelectOption> getOptions() { List<SelectOption> options = new List<SelectOption>(); Schema.DescribeFieldResult fieldResult = Opportunity.StageName.getDescribe(); List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues(); options.add(new SelectOption('--Select--', '--Select--')); for( Schema.PicklistEntry f : ple) { //system.debug('f.getLabel()=>'+f.getLabel() +' ==f.getValue()' +f.getValue()); options.add(new SelectOption(f.getLabel(), f.getValue())); } return options; } /** * Remote action involved with Javascript remoting and is made global **/ @RemoteAction global static Opportunity[] getOpportunityDetails(String stageNameDet) { return [select id,Name,Amount,stageName from Opportunity WHERE stageName =: stageNameDet]; } }



Post a Comment

| ,