Thursday, September 6, 2018

Init Event in Salesforce Lightning

This is also called as the constructor of lightning component.The init method is called once the component construction is over, as an example if i am creating a simple registration page and i want to display some default text value after page load in my input boxes i can do this by calling the javascript controller method and setting some default value in the attributes.
                          
Basic Syntax:

<aura:handler  name="init" value="{!this}" action="{!c.doinit}"/>

Let's take an example where we will be setting some default values in map type attribute and then displaying it.

Step 1) Build a lightning Component,

<aura:component controller="Mapvalue"  >

    <aura:handler  name="init" value="{!this}" action="{!c.doinit}"/>
 
        <aura:attribute type="map" name="Mapuse"/>  // Map type attribute to hold map value
       
        {!v.Mapuse.key1} 
        {!v.Mapuse.key2}
        {!v.Mapuse.key3}
</aura:component>


Note:// The init method get's call after construction of component is over and will call doinit method in javascript controller.



Step 2: Under javascript controller,

({
doinit : function(component, event, helper) {    //  component, event, helper are parameter                                                                                                of doinit function
       
      var action=  component.get('c.getmymap');  // Calling apex method
        action.setCallback(this,function(response)   // getting response back from apex method
        {
                  var state=response.getState();            // getting the state
        if(state==='SUCCESS')
        {
            component.set('v.Mapuse',response.getReturnValue());    // setting the value in attribute
           
        }
                         
                         
        });
$A.enqueueAction(action);

}
})



Step 3:Build apex controller.

public class Mapvalue {
    @AuraEnabled     // Method must be AuraEnabled in apex
    public static map<string,string> getmymap()
    {
        map<string,string> putkeyvalue= new map<string,string>();
        putkeyvalue.put('key1', 'Value1');
         putkeyvalue.put('key2', 'Value2');
         putkeyvalue.put('key3', 'Value3');
        return putkeyvalue;
    }

}


Step 4: Previewing with application.


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

</aura:application>

After preview,


Init Event in Salesforce Lightning

No comments:

Post a Comment