Thursday 30 August 2018

Invoke Apex from Lightning Component | how to call an Apex class from a Lightning component


In this post we will talk about how to call Apex class from Lightning Component.


Step 1) Create on Apex Class with @AuraEnabled annotation and method must be static.

public with sharing class UserController {
    @AuraEnabled
    public static List<User> getUserList() {
        return [Select id,name,email FROM User ];
    }
}

Step 2) Create Lightning Component with controller.
  • Add Controller attribute in <aura:Component tag to link the Apex Class like <aura:component controller="CLASSNAME">
  • Define <aura:Attribute tag to get value and to display value in Lightning page
  • Call Java Script doInit method to with <aura:handler" like <aura:handler name="init" value="{!this}" action="{!c.doInit}" />

<aura:component controller="UserController">
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>   
    <aura:attribute name="userList" type="List" />
    <table class="slds-table slds-table_bordered slds-table_striped slds-table_cell-buffer slds-table_fixed-layout">
            <thead>
              <tr class="slds-text-heading_label">
                <th scope="col"><div class="slds-truncate" title="ID">ID</div></th>
                <th scope="col"><div class="slds-truncate" title="Name">Name</div></th>
                <th scope="col"><div class="slds-truncate" title="Type">Email</div></th>
              </tr>
            </thead>
            <tbody>
              <!-- Use the Apex model and controller to fetch server side data -->
              <aura:iteration items="{!v.userList}" var="usr">
                  <tr>
                      <th scope="row"><div class="slds-truncate" title="{!usr.Id}">{!usr.Id}</div></th>
                      <td><div class="slds-truncate" title="{!usr.Name}">{!usr.Name}}</div></td>
                      <td><div class="slds-truncate" title="{!usr.Email}">{!usr.Email}</div></td>
                  </tr>
              </aura:iteration>
            </tbody>
    </table>   
</aura:component>   



Step 3) In Java Script Controller method call the helper JS method like below
 
({
    doInit : function(component, event, helper) {
        helper.getUserList(component);
    },
})

Step 4) As per best practice use Helper method for all logic.
  • Call Apex Class method with component.get("c.getUserList");
  • Then Set the callback method in queue like action.setCallback(this, function(response) { ... });
  • If call is successful then set the result in <aura:Attribute like  component.set("v.userList", response.getReturnValue());

({
    getUserList : function(component) {
        var action = component.get("c.getUserList");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.userList", response.getReturnValue());
            }
            else {
                console.log("Failed with state: " + state);
            }
        });
        $A.enqueueAction(action);
    } ,

})

Step 5) Create one Application to test the result.

<aura:application extends="force:slds">
    <c:UserDetails />
</aura:application>   

Here is output.




Thanks
Amit Chaudhary

Sunday 26 August 2018

Dynamic Picklists in Custom Component Property | VisualEditor.DynamicPickList | Dynamic Picklists in Lightning with Apex



We can create a component property as a picklist to configure the component in the Lightning App Builder. With the help of "VisualEditor.DynamicPickList" we can create a dynamic picklist and can fetch the data from Sobject/Custom Setting as well.

In our previous post we talk about "Design Resource" and created one "favoriteColors" "design:attribute" to create picklist. In that post we provided the hardcoded value in "datasource". Let see how to add Dynamic value in Picklist Property.

Step 1) Create on Apex class and Extend the VisualEditor.DynamicPickList abstract class.

 DynamicPicklistController Apex Class

global class DynamicPicklistController extends VisualEditor.DynamicPickList{
    global override VisualEditor.DataRow getDefaultValue(){
        VisualEditor.DataRow defaultValue = new VisualEditor.DataRow('red', 'RED');
        return defaultValue;
    }
    global override VisualEditor.DynamicPickListRows getValues() {
        VisualEditor.DynamicPickListRows  myValues = new VisualEditor.DynamicPickListRows();
        List<Color__c> listColor = [SELECT Name,ColorCode__c FROM Color__c limit 10 ];
        for(Color__c col: listColor){
            myValues.addRow(new VisualEditor.DataRow(col.ColorCode__c, col.Name));
        }
        return myValues;
    }
}

Step 2) Add an Attribute to your Design File.

DynamicPicklist.design

<design:component>
    <design:attribute name="favoriteColors"  label="Color" datasource="apex://DynamicPicklistController"/>
</design:component>

DynamicPicklist.cmp

<aura:component implements="flexipage:availableForAllPageTypes,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" >
   <aura:attribute name="favoriteColors" type="String" access="global"/>
   <div >
        <div class="slds-text-heading_large" style="{!'color:' + v.favoriteColors}" >
            Welcome In Lightning
        </div>
   </div>
</aura:component>

Here is result








Thanks,
Amit Chaudhary
Capture.JPG  @amit_sfdc    #SalesforceApexHours    @ApexHours
  Salesforce Apex Hours