When developing Lightning Components on the Salesforce platform a popular need is to simply display values from an apex controller directly on the lightning component.
To help show how to do this I created this example where the lightning component is displaying field values returned form a SOQL query.
Summary:
- We create our string and object get;set; variables and a include the @AuraEnabled annotation.
- The @AuraEnabled annotation enables client- and server-side access to an apex controller method and controller property. Providing this annotation makes your methods and properties available to your Lightning components.
- In the Apex class LC_controller we have a single method initClass() where the return type is class type / the object itself.
Apex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class LC_controller { @AuraEnabled public String accfield { get;set; } @AuraEnabled public Account currentRecord { get;set; } @AuraEnabled public static LC_controller initClass() { //create class instance LC_controller obj = new LC_controller(); obj.currentRecord = [SELECT Id,name FROM Account order by CreatedDate desc limit 1]; obj.accfield = obj.currentRecord.name; // return class instance return obj; } } |
Lightning Component:
1 2 3 4 5 6 7 8 |
<aura:component controller="LC_controller" implements="forceCommunity:availableForAllPageTypes,flexipage:availableForAllPageTypes,force:hasRecordId" access="global"> <aura:handler name="init" value="{!this}" action="{!c.doInit}"/> <aura:attribute name="objClassController" type="LC_controller"/> The value passed from the apex controller: {!v.objClassController.accfield} </aura:component> |
Lightning Component Controller JS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
({ doInit: function(component, event, helper) { //call apex class method var action = component.get('c.initClass'); action.setCallback(this, function(response) { //store state of response var state = response.getState(); if (state === "SUCCESS") { //set response value in objClassController attribute on the component component.set('v.objClassController', response.getReturnValue()); } }); $A.enqueueAction(action); }, }) |