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.status==>'+event.status);
          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});
    }
    </script>
    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>
            <apex:pageBlockSectionItem id="theSecondItem" >
                <apex:outputText id="accNam" />
            </apex:pageBlockSectionItem>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>

Controller Class:

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


Out Put:

RemoteAction


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="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></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]; } }


Output:











6 comments:

21cssIndia said...

Salesforce Admin Corporate Training | Online Training by real time Experts with IT Support IND: 910-0934572. Online Training classes gives you complete knowledge by 21st Century. send ur enquiry to contact@21cssindia.com. or Call +917386622889 http://www.21cssindia.com/salesforce-admin-training Salesforce Admin Training| USA:201-210-8616|Online/Corporate training|21cssindia 

CyberEddie said...

@RemoteAction //This exposes method to javascript remoting
public static List oppList(){

return [SELECT Id, Name, Amount, Owner.name, Account.name, Acct_Billing_State__c, CloseDate,
(SELECT Date__c, Quantity__c,product__r.Name FROM Schedules__r WHERE Date__c != null AND Quantity__c>1 ORDER BY Date__c)
FROM Opportunity
WHERE (Opportunity.CloseDate = NEXT_N_MONTHS:5 OR
Opportunity.CloseDate = THIS_MONTH) AND
(Amount > 1 AND Name != null)
ORDER BY
CloseDate ASC,
Name ASC
];


I have this question, how do I reference the fields from a multiple select ??

Unknown said...

good post very useful but while i iam implementing the second example opportunity name is not populated in the table how can i do that?

Unknown said...

Thanks for providing such useful information on salesforce training

candy lol said...

I was more than happy to find this web site.


Facebookvideodownloader.org

nick jones said...

good blog..
Server and Storage Solutions

Post a Comment

 
| ,