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:
Apex Code:
- public class OpportunityController {
- @AuraEnabled
- public static List<Opportunity> getOpportunities() {
- List<Opportunity> opportunities =
- [SELECT Id, Name, CloseDate FROM Opportunity];
- return opportunities;
- }
- }
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. Create a lightning component with the below code snippet. Controller attribute in the aura:component refers the apex class.
- <aura:component controller="OpportunityController">
- <ui:button label="Get Opportunities" press="{!c.getOpps}"/> <br/>
- <aura:iteration var="opportunity" items="{!v.opportunities}">
- <p>{!opportunity.Name} : {!opportunity.CloseDate}</p> <br/>
- </aura:iteration>
- </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.
- ({
- getOpps: function(cmp){
- var action = cmp.get("c.getOpportunities");
- action.setCallback(this, function(response){
- var state = response.getState();
- if (state == "SUCCESS") {
- cmp.set("v.opportunities", response.getReturnValue());
- }
- });
- $A.enqueueAction(action);
- }
- })
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