Thursday, April 5, 2018

Calling Apex class from lightning component without Base Component

Step 1: 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 2 : create a component with the name "CallApexclass"

==========



<aura:component controller="ApexController">



    <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 3 :copy following code in the JS controller

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



({

 Condata : function(cmp) {

        // Load all contact data

        var action = cmp.get("c.getContacts");

        action.setCallback(this, function(response) {

            var state = response.getState();

            if (state === "SUCCESS") {

                  console.log('%%%%%%%%%% Contact'+JSON.stringify(response.getReturnValue()));

           

            }

       

        });

   

   

         $A.enqueueAction(action);

    },

        Condataname : function(cmp) {

        // Load all contact data

        var action = cmp.get("c.getContactsbyName");

            action.setParams({name:cmp.find("conid").get("v.value")});

        action.setCallback(this, function(response) {

            var state = response.getState();

            if (state === "SUCCESS") {

                  console.log('%%%%%%%%%% Contact'+JSON.stringify(response.getReturnValue()));

           

            }

       

        });

       

       

         $A.enqueueAction(action);

    },

 

    Leaddata : function(cmp) {

        // Load all contact data

        var action = cmp.get("c.getLeads");

        action.setCallback(this, function(response) {

            var state = response.getState();

            if (state === "SUCCESS") {

                console.log('%%%%%%%%%% lead'+JSON.stringify(response.getReturnValue()));

           

            }

       

        });

         $A.enqueueAction(action);

    },

     Accdata : function(cmp) {

        // Load all contact data

        var action = cmp.get("c.getAccounts");

     

        action.setCallback(this, function(response) {

            var state = response.getState();

            if (state === "SUCCESS") {

                  console.log('%%%%%%%%%% Account'+JSON.stringify(response.getReturnValue()));

           

            }

       

        });

     

         $A.enqueueAction(action);

    }

 

})



===========

Step 4: create App to test it



<aura:Application>



<c: CallApexclass/>



</aura:Application>



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>

Monday, April 2, 2018

Bound and UnBound Expressions

When you add a component in markup, you can use an expression to initialize attribute values in the component based on attribute values of the container component. There are two forms of expression syntax, which exhibit different behaviors for data binding between the components.

Using Delimiter  "{!}"  Makes an attribute as bound and using Hash "{#}" Makes an attribute as unbound.
When ever possible we need to use Hash "{#}" as a best practice which in turn improves performance.

Example:

<!--Bound Expression -->
    <c:ChildExp mynum="{!v.parentattribute}"/> 

<!--Unbound Expression -->
    <c:ChildExp mynum="{#v.parentattribute}"/>

This concept is a little tricky, but it will make more sense when we look at an example.
 ===================
ChildExp Markup
===================
<aura:component >
    <aura:attribute name="mynum" type="String" />
    
    <lightning:card title="Child Card" >
    <lightning:input label="Child input" value="{!v.mynum}" />
        <aura:set attribute="actions">
            <lightning:button onclick="{!c.Bckgrnd}"  label="Check Back ground data" variant="brand"/>
        
        </aura:set>
    </lightning:card>
   
    
</aura:component>
===================
ChildExp Controller
===================

({
Bckgrnd : function(component, event, helper) {
            var mydata=component.get('v.mynum');
        
}
})


===============
ParentExp Markup
================

<aura:component >
    <aura:attribute name="parentattribute" type="String" default=" I like lightning " />
    
    <lightning:card title="Parent Card" >
        
    <lightning:input value="{!v.parentattribute}" label="Parent input"/>
    </lightning:card> 
     <br/>
     <br/>

<!--Bound Expression -->
    <c:ChildExp mynum="{!v.parentattribute}"/> 

<!--Unbound Expression -->
    <c:ChildExp mynum="{#v.parentattribute}"/>
</aura:component>

===============
ParentExpApp to test the scenario
================

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

Initial output








After changing the data in the child input component


Tuesday, March 27, 2018

VF code vs Lightning code.

<apex:page controller="Mycalci">
    <apex:form >
        <apex:pageBlock >
       
  First Number      <apex:inputText value="{!num1}"/>
       
  Second Number         <apex:inputText value="{!num2}"/>
 
 
 Out put <apex:outputText value="{!num3}" label="Out put"/>
 
  <apex:pageBlockButtons >
 
  <apex:commandButton value="Add" action="{!Add}"/>
    <apex:commandButton value="Sub" action="{!sub}"/>
  </apex:pageBlockButtons>
         
        </apex:pageBlock>
    </apex:form>
</apex:page>

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

public class Mycalci {

    public Integer num1 { get; set; }
    public Integer  num2 { get; set; }
    public Integer  num3{ get; set; }
   
   
    public pageReference Add()
    {
   
    num3=num1+num2;
   
    return null;
    }
   
   
    public void Sub()
    {
   
    num3=num1-num2;
   
   
    }
   
}

============
lighting component
=======

<aura:component implements="flexipage:availableForAllPageTypes" access="global" >
   
   
    <aura:attribute name="num1" type="integer" />
    <aura:attribute name="num2" type="integer" />   
    <aura:attribute name="num3" type="integer" />
   
     <lightning:input name="input1" label="Enter first number" type="number" value="{!v.num1}" aura:id="abc"/>
   
     <lightning:input name="input2" label="Enter second number" type="number" value="{!v.num2}" aura:id="xyz"/>
   
      <ui:inputNumber label="Number 1" value="{!v.num1}" aura:id="ddd" />
   
  {!v.num1} +{!v.num2}
   
<lightning:buttonGroup >
     
        <lightning:button label="Add" variant="success" onclick="{!c.Add}" title="Add Method"  />
        <lightning:button label="Sub" variant="brand" onclick="{!c.Sub}"  />
        <lightning:button label="Mul" variant="destructive"  onclick="{!c.Mul}"  />
    </lightning:buttonGroup>
   
   
</aura:component>

===========
Java script Controller code
===========


({
Add : function(component, event, helper) {
       
      var n1=parseInt(component.find("abc").get("v.value"));
 
         var n2=parseInt(component.find("xyz").get("v.value"));
       
         var n3=component.find("ddd").get("v.value");
       
        alert(n3);
       
    var a=  parseInt(component.get('v.num1'));
    var b=  parseInt(component.get('v.num2'));
    var c=n1+n2;
       
        var d= a+b;
       
        alert('%%%%%final out put%%%%%'+d);
       
       
       
       
     
     

},
    Sub : function(component, event, helper) {
       
       var n1=parseInt(component.find("abc").get("v.value"));
 
         var n2=parseInt(component.find("xyz").get("v.value"));
       
         var c=n1-n2;
       
        alert('%%%%%final out put%%%%%'+c);

},
    Mul : function(component, event, helper) {
       
            var n1=parseInt(component.find("abc").get("v.value"));
 
         var n2=parseInt(component.find("xyz").get("v.value"));
       
         var c=n1*n2;
       
        alert('%%%%%final out put%%%%%'+c);


}
   
})

Component References for Lighting


For getting your org Components source code, please replace below domain name with your domain name.

https://lightningclass1000-dev-ed.lightning.force.com/auradocs/reference.app

For getting all the OOTB(our of box) components, please replace below domain name with your domain name.


To understand the Secure versions of essential Java Script DOM API's, such as Window.. click on below link>

http://documentation.auraframework.org/lockerApiTest/index.app?aura.mode=DEV

Sunday, February 25, 2018

Covered Aura:Method, Aura.Action, ParenttoChild, ChildtoParent and Sibling Communication.

Below code Covers Aura:Method, Aura.Action, ParenttoChild, ChildtoParent and Sibling Communication in one Single Application.



Step 1:

=========
componentEvents
=========
<aura:event type="COMPONENT" description="Event template" >
 
    <aura:attribute name="firstnumber" type="Integer" />
     <aura:attribute name="secondnumber" type="Integer" />
 
</aura:event>

Step 2:
==============
childcomp
===========
<aura:component>
  <aura:attribute name="childoutput" type="Integer" />

  <aura:attribute name="clickme" type="Aura.Action" />

  <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
  <aura:registerEvent name="cmp1" type="c:componentEvents" />
 
 
   <lightning:card title="Child 1">
 
  <lightning:input type="integer" label="Number 1" aura:id="num1" />
  <lightning:input type="integer" label="Number 2" aura:id="num2" />

  <p
    ><lightning:button
      label="Component Event"
      onclick="{!c.fireComponentEvent}" variant="brand"
    />
  </p>

  <p
    ><lightning:button
      label="Parent Method calling with Aura.action"
      onclick="{!v.clickme}" variant="brand"
    />
  </p>
     
       </lightning:card>
</aura:component>

==============
childcomp controller
===========

({
child : function(component, event, helper) {
     
        var output=parseInt(event.getParam("firstnumber")) +parseInt(event.getParam("secondnumber"));
     
       component.set("v.childoutput",output);

},
 
    fireComponentEvent : function(component, event) {
        // Get the component event by using the
        // name value from aura:registerEvent
    var cmpEvnt=component.getEvent("cmp1");
    var num1=parseInt(component.find("num1").get("v.value"));
    var num2=parseInt(component.find("num2").get("v.value"));
     
    cmpEvnt.setParams({"firstnumber":num1,"secondnumber":num2});
        cmpEvnt.fire();
    },
    doInit :function(component, event, helper){
     
       // component.set("v.childoutput",10000);
    }

})

Step 3:

=========
childcomp2
========

<aura:component >
 
     <aura:attribute name="prntoutput" type="Integer" default="0"/>
    <aura:method name="Addition" action="{!c.Addition}" description="Sample method with parameters">
    <aura:attribute name="param1" type="Integer" />
    <aura:attribute name="param2" type="Integer" />
    </aura:method>
    <br/>
    <br/>
    <br/>
     <lightning:card title="Child 2">
    <p>Sibling out put</p>
    {!v.prntoutput}
    <br/>
    <br/>
    <br/>
    </lightning:card>
</aura:component>

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

({
Addition : function(component, event, helper) {
         var params = event.getParam('arguments');
        if (params) {
            var param1= params.param1;
            var param2= params.param2;
            var output=param1+param2;
        }
     
        component.set("v.prntoutput",output);

}
})

Step 4:

parentComp
==========
<aura:component >
    <aura:attribute name="prntoutput" type="Integer" />
  <aura:handler name="cmp1" event="c:componentEvents" action="{!c.parent}" />
 
    <lightning:card title="Parent output">
 
    {!v.prntoutput}
 
   </lightning:card>
     <br/>
    <br/>
    <br/>
 
     <c:childcomp />

     <c:childcomp2 aura:id="sibling"   />
 
 
 
   <!--   <c:childcomp clickme="{!c.Parentmethod}"  />  -->
 
   <!--   <c:childcomp cmp1="{!c.parent}"/> -->

 
</aura:component>


====
parentComp controller
=====

({
parent : function(component, event, helper) {
     
        var fnumber=parseInt(event.getParam("firstnumber"));
        var snumber=parseInt(event.getParam("secondnumber"));
        var output=fnumber+snumber;
     
       component.set("v.prntoutput",output);
     
        var childCmp = component.find("sibling");

      childCmp.Addition(fnumber,snumber);
     
     

},
    Parentmethod:function(component, event, helper) {
     
      alert("From Parent Method");
     
     

}
})

Step 5:
==================
Grantparent
==============

<aura:component implements="flexipage:availableForAllPageTypes" >
    <aura:attribute name="prntoutput" type="Integer" />
     <aura:attribute name="parentdata" type="Integer" default="100000" />
     <aura:handler name="cmp1" event="c:componentEvents" action="{!c.Grandparent}" />

    <lightning:card title="Grand Parent Output">
 
    {!v.prntoutput}
    <br/>
    <br/>
    <br/>
    <c:parentComp  prntoutput="{!v.parentdata}" />
     
    </lightning:card>
</aura:component>

==================
Grantparent controller
==============

({
Grandparent : function(component, event, helper) {
     
        var output=parseInt(event.getParam("firstnumber")) +parseInt(event.getParam("secondnumber"));
   
       component.set("v.prntoutput",output);
     
     

}
})

Step 6:
=========
Alleventsapp
=======

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


For another advance way of communication on top of these topics, please refer here: https://davesfdc.blogspot.com/2018/10/another-advanced-way-of-parent-to-child.html

Salesforce Lightning: Application Events (Sample Siri)

Application events follow a traditional publish-subscribe model. An application event is fired from an instance of a component. All components that provide a handler for the event are notified.


Step 1 : create Application event

/* Use type="APPLICATION" in the <aura:event> tag for an application event. For example, this c:appEvent application event has one attribute with a name of message. */

===============================
ApplicationCommunication  Event
================================


<aura:event type="APPLICATION" description="Discussion between multiple Components" >
 
    <aura:attribute name="mesg" type="string" />
 
 
</aura:event>


Step 2:  Create Source Component

/*A component registers that it may fire an application event by using <aura:registerEvent> in its markup. The name attribute is required but not used for application events. The name attribute is only relevant for component events. This example uses name="appEvent" but the value isn’t used anywhere.*/

Name: SourceCmp
==================

<aura:component implements="flexipage:availableForAllPageTypes">
 
    <aura:registerEvent name="anyname" type="c:ApplicationCommunication" />
    <aura:attribute name="Display" type="boolean" default="false" />
    <aura:attribute name="greeting" type="string" />
    <lightning:input type="string" label="Enter some data here"  aura:id="inputdata"/>
    <p><lightning:button label="Click here to fire an application event"
        onclick="{!c.fireApplicationEvent}" />
    </p>


</aura:component>

Step 3: copy paste below code in the SourceCmp  client side controller
======
SourceCmp controller side code
========
({
fireApplicationEvent : function(component, event, helper) {
     
        var message=component.find("inputdata").get("v.value");
     
        var appEvent=$A.get("e.c:ApplicationCommunication");
     
        appEvent.setParams({"mesg":message});
     
        appEvent.fire();
     
 

}
})


Step 4: Listener or Handler Markup code

/*Use <aura:handler> in the markup of the handler component.

For example:

<aura:handler event="c:appEvent" action="{!c.handleApplicationEvent}"/>*/

==========
Name: Listener (Handler)
===========
<aura:component implements="flexipage:availableForAllPageTypes" access="global" >
    
    <aura:attribute name="receivedevent" type="string"  />
    
    <aura:handler event="c:ApplicationCommunication" action="{!c.handleApplicationEvent}" />
    
     <p>{!v.receivedevent}</p>

    
</aura:component>


Step 5:


==================
Listener client side controller
==================
({
    handleApplicationEvent : function(cmp, event) {
      var Sourcedata= event.getParam("mesg");
        var response="Sorry I did not understand you";
        if(Sourcedata=='Hi')
        {
            response="Hello"
        } 
         if(Sourcedata=='How are you')
        {
            response="Im doing great!!"
        } 

         if(Sourcedata=='How is your course')
        {
            response="Going good"
        } 
         if(Sourcedata=='Do practice after this session')
        {
            response="Sure Thank you !!"
        } 
         if(Sourcedata=='Good Night')
        {
            response="Good night too, sweet dreams !!"
        } 
         if(Sourcedata=='Good Morning')
        {
            response="Good Morning too, have a great day !!"
        } 

            
        cmp.set("v.receivedevent",response);
    }

})


Step 6:  create Application with the below code

<aura:application >
    <c:SourceCmp />
    <c:Listener  />
</aura:application>


Step 7: Instead of above 6th step code I recommend to Surface SourceCmp and Listener  on different parts of the Application builder page. Though there is no connection between these components but still you can create communication  between these two components.