Monday, 23 November 2015

Lightning Component Client and Server Interaction Example in Salesforce

This article will explain about the Client(Javascript) and Server(Apex) side communication. The below example will retrieve opportunity records from the server and displayed the values on Lightning app using aura:iteration tag.

Apex Code:

  1. public class OpportunityController {
  2.     @AuraEnabled
  3.     public static List<Opportunity> getOpportunities() {
  4.         List<Opportunity> opportunities =
  5.                 [SELECT Id, Name, CloseDate FROM Opportunity];
  6.         return opportunities;
  7.     }
  8. }

Note: 

  • @AuraEnabled annotation used to access the variable/method names in Lightning Component.
  • Methods must be static and marked public or global. Non-static methods are not supported.
  • If a method returns an object, instance methods that retrieve the value of the object’s instance field must be public.
Lightning Component Code:

1. Create a lightning component with the below code snippet. Controller attribute in the aura:component refers the apex class.

  1. <aura:component controller="OpportunityController">
  2.     <ui:button label="Get Opportunities" press="{!c.getOpps}"/> <br/>
  3.     <aura:iteration var="opportunity" items="{!v.opportunities}">
  4.         <p>{!opportunity.Name} : {!opportunity.CloseDate}</p> <br/>
  5.     </aura:iteration>
  6. </aura:component>

Note:
a. This component contain Button labeled as "Get Opportunities". Once if you click this button, it will call a "getOpps" javascript controller.

b. aura:iteration used to iterate the returned array list.

2. Double click on CONTROLLER from the side bar in lightning component editor and paste the below java script snippet.

  1. ({
  2.     getOpps: function(cmp){
  3.         var action = cmp.get("c.getOpportunities");
  4.         action.setCallback(this, function(response){
  5.             var state = response.getState();
  6.             if (state == "SUCCESS") {
  7.                 cmp.set("v.opportunities", response.getReturnValue());
  8.             }
  9.         });
  10.         $A.enqueueAction(action);
  11.     }
  12. })

Note:
a. This  javascript calls "getOpportunities" method from "OpportunityController" and returned a list of opportunity records.
b. Returned values assigned to the "v.opportunities" variable. This list iterated using aura:iteration tag.

No comments:

Post a Comment

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...