Sunday, 6 June 2021

Remote Action in Salesforce

 Remote Action is a way to access Apex method using Javascript in your Visualforce page.

It allows you to create pages with complex, dynamic behavior that isn’t possible with the standard Visualforce AJAX components.


Remote action method should always have the @RemoteAction annotation and it should be Static.


public with sharing class CasePriority {

    @RemoteAction

    public static list<Case> getCases(string priority) {

        list<Case> cases = [Select Id, CaseNumber, Subject, Description, Priority, Status 

                              From Case 

                              Where Priority = :priority

                              And Status = 'New'

                              Limit 5];

        if (cases.isEmpty()){

            return new list<Case>();

        }

        return cases;

    }

}


ex :



<apex:page controller="CasePriority" lightningStylesheets="true">

    <script type="text/javascript">

    function getCases(priority) {

        Visualforce.remoting.Manager.invokeAction(

            '{!$RemoteAction.CasePriority.getCases}', priority,

            function(result, event){

                if(event.status){

                    var html = '<table>';

                    html += '<tr><th>Case Number</th><th>Subject</th><th>Priority</th></tr>';

                    result.forEach(function(item){

                        html += '<tr>';

                        html += '<td>'+ item.CaseNumber +'</td>';

                        html += '<td>'+ item.Subject +'</td>';

                        html += '<td>'+ item.Priority +'</td>';

                        html += '</tr>';

                    })

                    html += '</table>';

                    document.getElementById('results').innerHTML = html;

                }           

            },

            {escape: true}

        );

    }

    </script>

    

    <apex:pageblock id="block">

        <apex:pageblockbuttons location="top" >

            <apex:form>

            <apex:commandButton value="High" onclick="getCases('High'); return false;" />

                <apex:commandButton value="Medium" onclick="getCases('Medium'); return false;"/>

                <apex:commandButton value="Low" onclick="getCases('Low'); return false;"/>

            </apex:form>

            

        </apex:pageblockbuttons>

        

        <apex:pageblocksection columns="1" id="blockSection">

            <div id="results">

                

            </div>

        </apex:pageblocksection>

    </apex:pageblock>

</apex:page>


Notes :


1.@RemoteAction annotation is mandatory

2.Remote Action methods should always be static

3.If you are using the Visualforce Page inline in a Page Layout, then the method should be declared as global instead of public.



Key Features are: 


1.Remote Action is a static method

2.Bandwidth Usage is less

3.View state is not maintained

No comments:

Post a Comment