Thursday, April 5, 2018

Calling apex class from the Lightning component with the Base Utility helper methods

Step 1: Create a base lightning component with the Name "Base"

============================

<aura:component abstract="true">

 {!v.body}

</aura:component>



===============================

step 2: Copy following code in the helper file of above base component and it would be sufficient to make any apex server calls. You dont need to write repeated code again and again to hit the server.



Note: Reason why we are keeping below code in the Helper instead of Component.Js is, we cannot reuse the Component.Js file functions. Only Helper file will be used for re-usability purpose.



===============================

({

    callServer : function(component,method,callback,params) {

        var action = component.get(method);

        if (params) {

            action.setParams(params);

        }

     

        action.setCallback(this,function(response) {

            var state = response.getState();

            if (state === "SUCCESS") {

                // pass returned value to callback function

                callback.call(this,response.getReturnValue());

            } else if (state === "ERROR") {

                // generic error handler

                var errors = response.getError();

                if (errors) {

                    console.log("Errors", errors);

                    if (errors[0] && errors[0].message) {

                        throw new Error("Error" + errors[0].message);

                    }

                } else {

                    throw new Error("Unknown Error");

                }

            }

        });

     

        $A.enqueueAction(action);

    }

})





=========================================

Step 3: create apex class with the name "ApexController" and copy the below code.

=========================================



public with sharing class ApexController {

@AuraEnabled

    public static List<Contact> getContacts() {

        List<Contact> contacts =

                [SELECT Id, Name, MailingStreet, Phone, Email, LeadSource FROM Contact];



        //Add isAccessible() check

        return contacts;

    }

 @AuraEnabled 

    public static List<Lead> getLeads() {

        List<Lead> leads =

                [SELECT Id, Name FROM Lead];



        //Add isAccessible() check

        return leads;

    }

    @AuraEnabled

    public static List<Account> getAccounts() {

        List<Account> Accounts =

                [SELECT Id, Name FROM Account];



        //Add isAccessible() check

        return Accounts;

    }

       @AuraEnabled

     public static List<Contact> getContactsbyName(string name) {

     string nam=name;

        List<Contact> contacts =

                [SELECT Id, Name, MailingStreet, Phone, Email, LeadSource FROM Contact where Name=:nam];



        //Add isAccessible() check

        return contacts;

    }

}





Step 4 : create a component with the name "CallApexclassCmpBase"

==========



<aura:component controller="ApexController" extends="c:Base">

 

    <lightning:card title="Bring Account data">

     

          <aura:set attribute="actions">

     

              <lightning:button label="Acc Data" onclick="{!c.Accdata}" />

          </aura:set>

 

    </lightning:card>

 

     <lightning:card title="Bring Contact data">

     

          <aura:set attribute="actions">

     

              <lightning:button label="Contact Data" onclick="{!c.Condata}" />

          </aura:set>

 

    </lightning:card>

 

    <lightning:card title="Bring Lead data">

     

          <aura:set attribute="actions">

     

              <lightning:button label="Lead Data" onclick="{!c.Leaddata}" />

          </aura:set>

 

    </lightning:card>

 

    <lightning:card title="Bring Contact data with name">

        <lightning:input aura:id="conid" label="Enter Contact Name" />

          <aura:set attribute="actions">

     

              <lightning:button label="Contact Data" onclick="{!c.Condataname}" />

          </aura:set>

 

    </lightning:card>



</aura:component>

==========================================================

Step 5 :copy following code in the JS controller

==========================================================



({

 Condata : function(component,event,helper) {

 helper.callServer(

            component,

            "c.getContacts",

            function(response) {

               console.log('%%%%%% Contacts data '+JSON.stringify(response));

            }

        );

   

    },

        Condataname : function(component,event,helper) {

  helper.callServer(

            component,

            "c.getContactsbyName",

            function(response) {

               console.log('%%%%%% Contacts by name '+JSON.stringify(response));

            }, {

                name:component.find("conid").get("v.value")

            }

        );

     

    },

 

    Leaddata : function(component,event,helper) {



  helper.callServer(

            component,

            "c.getLeads",

            function(response) {

               console.log('%%%%%% Leads data '+response);

            }

        );

   

    },

     Accdata : function(component,event,helper) {

       helper.callServer(

            component,

            "c.getAccounts",

            function(response) {

               console.log('%%%%%% Accounts data '+response);

            }

        );

    }

 

})

===========

Step 6: create App to test it



<aura:Application>



<c: CallApexclassCmpBase/>



</aura:Application>

5 comments:

  1. I am getting an error as
    Uncaught Action failed: etaPrime:CallApexclassCmpBase$controller$Condata [helper.callServer is not a function]

    ReplyDelete
  2. Hi Krishna, Please Make sure that your Condata(component,event,helper) Method follow the proper sequence parameters as (component,event,helper). It should fix the problem.

    ReplyDelete
  3. Thank you so much for sharing these Salesforce Real time Scenarios and release exams. I have also done salesforce training
    . Keep blogging and rocking !

    ReplyDelete
  4. What format should be followed to pass parameters from child to base component

    ReplyDelete
  5. Any sample for passing the parameters?

    ReplyDelete