Tuesday, April 30, 2019

How to create lighting components in salesforce:full example

In this component we will see how to create a lightning component

Steps.
1.Open developer console from setup

2. Create new Lightning Component

3. The lightning bundle will get created


4. Now add the attributes (variables) and markup in the component section

Copy this code to the component sections
<aura:component controller="ContactController" implements="force:appHostable,flexipage:availableForAllPageTypes"    access="global">
    <aura:attribute name="Amount" type="double" default="25000"/> 
    <aura:attribute name="Tenure" type="double" default="16"/>
    <aura:attribute name="Maturity" type="double" default="34"/>
    <aura:attribute name="accid"  type="String" default=""/>
    <aura:attribute name="accountName" type="String" default=""/>
    <aura:attribute name="Conid"  type="String" default=""/>
    <aura:attribute name="ContactName" type="String" default=""/>
    <aura:attribute name="contactlist" type="Contact[]"/>
    <aura:attribute name="errmess" type="String" default="Error message"/>
     <aura:attribute name="messageToJSApp" type="String" />
    <aura:attribute name="messageFromJSApp" type="String" />

 
    <aura:handler name="change" value="{!v.Tenure}" action="{!c.fieldvalidornot}"/>
 
 
 
 
    <aura:handler name="change" value="{!v.Conid}" action="{!c.getcontactname}"/>
   <!-- <aura:handler name="change" value="{!v.Tenure}" action="{!c.tenurechanged}"/>-->
    <!--<aura:handler name="render" value="{!this}" action="{!c.onRender}"/>-->
    <aura:handler name="init" value="{!this}" action="{!c.oninit}"/>
    <aura:handler name="change" value="{!v.accid}" action="{!c.getacccontacts}"/>
    <!--   <aura:handler name="change" value="{!v.tenure}" action="{!c.calculate1}"/>-->
    <!-- Remember everything is case sensitive --> 
    <aura:attribute name="Designresourcestring" type="String" />
    <!-- <lightning:container aura:id="AngularApp1"  onmessage="{!c.handleMessage}" src="{!$Resource.angularapp1 + '/index.html'}"       />
      <lightning:container aura:id="AngularApp2"  onmessage="{!c.handleMessage}" src="{!$Resource.angularapp2 + '/index.html'}"       />
     -->
           <div >
      <!--  <c:facetheader >   
            <aura:set attribute="header1">
                Lightning Form from another comp
            </aura:set>
        </c:facetheader> -->     
        <!--Lightning Form-->
        <ui:inputText class=".colorme" label="Contactid" value="{!v.Conid}"/> 
        <ui:inputText label="Contactname" value="{!v.ContactName}"/>
        <ui:inputText  label="Accountid" value="{!v.accid}" /> 
        <ui:inputText label="AccountName" value="{!v.accountName}"/>
        <div aura:id="div2" class="toggle1">
            <ui:inputNumber label="Coupon amount" value="{!v.Amount}"/>
            <ui:inputNumber aura:id="tenure" label="Coupon Tenure" value="{!v.Tenure}"/>
        </div>
        <h2>Maturity Amount will be :</h2><ui:outputNumber value="{!v.Maturity}"/>
        <br/><ui:button label="Calculate coupon returns" press="{!c.calculate11}"/>
        <br/>     
        <br/> <lightning:button label="remove css"  onclick="{!c.remclass}"/>
        <!--<c:auraiterationcmp contactlist= "{!v.contactlist}"/>-->
     
     
      <!--  <ul class="list-group">
           
           
        <aura:iteration items="{!v.contactlist}" var="conl">
            <li>
                Contact Name {!conl.Name}
            </li>
        </aura:iteration>
    </ul>-->
    </div>
    <p aura:id="text1"  class="toggle1">   Dynamic text toggling </p>
</aura:component>

5. Next add this code to the controller section
({            getcontactname : function(component,event,helper){
            //this call's server side controller action        ////first get action variable intialised with controller method apex function
            var action = component.get("c.retcontactname");
          //  debugger; 
            action.setParams({ id: component.get("v.Conid") });
            action.setCallback(this, function(a) {         
                if(a.getReturnValue() == 'error'){
                    console.log('Error returned from apex');             
                }else{
                    component.set("v.ContactName", a.getReturnValue());
                }
               console.log(a.getReturnValue());
            });
            $A.enqueueAction(action);
        },
    getacccontacts : function(component,event,helper){
        //this call's server side controller action
        ////first get action variable intialised with controller method apex function
        var action = component.get("c.retaccountdetails");
        //debugger;   
        action.setParams({ id: component.get("v.accid") });
        action.setCallback(this, function(a) {
         
            var retx = a.getReturnValue().split(';');
            var accountname = retx[0];
            var contactname = retx[1]; 
            component.set("v.ContactName", contactname);
            component.set("v.accountName", accountname);
            //alert(a.getReturnValue());
        });
        $A.enqueueAction(action);
        //second call to populate list
         var action1 = component.get("c.retaccountdetailslist");
        debugger;   
        action1.setParams({ id: component.get("v.accid") });
        action1.setCallback(this, function(a) {
         
       
           component.set("v.contactlist",a.getReturnValue());
        });
        $A.enqueueAction(action1);
    }, 
    remclass : function(component,event,helper){
        $A.util.removeClass(component, 'changeMe');
     
        $A.util.addClass(component.find('text1'),'toggle1');
     
    },
    oninit:function(component,event,helper){
   
        alert('On INIt');
    },
    onRender :function(component,event,helper){
     
        alert('On Render event fired');
    },
    calculate11 : function(component, event, helper) {
          helper.sendMessage(component,event,helper)
     console.log('Inside the controller js'); 
    // helper.calculate2(component);
     helper.validate12(component,helper);
     
    },
 
    fieldvalidornot: function(component, event, helper){
     
        helper.validate12(component,helper);
     
    },
      /*   var inputcmp = component.find("tenure"); //or component.get("v.tenure";)
        var val  =inputcmp.get("v.value");
        console.log(inputcmp.get("v.label"));
        if(val >21){
         
           inputcmp.set("v.errors",[{message :'Value cant be greater than 21 using compset'}]);
            //add the line to remove class and show error message on text1
        }else{
     
        helper.calculate2(component); //move your calc code to helper and call from controller
          //  helper.showmessage1(component);
       $A.util.addClass(component, 'changeMe');
     //    $A.util.removeClass(component.find('text1'), 'toggle1');
         
     
        }

    }*/
    tenurechanged: function(component){
     
     
        console.log(component.get("v.Tenure"));
    },
 
    calculate1 : function(component,event,helper) {
        // debugger;
        var inputcmp = component.find("tenure");
      //  component.get("v.tenure";)
        var val  =inputcmp.get("v.value");
        console.log(inputcmp.get("v.label"));
        if(val >21){
            inputcmp.set("v.errors",[{message :'Value cant be greater than 21 using compset'}]);
            //add the line to remove class and show error message on text1
        }else{
            inputcmp.set("v.errors",[{message :''}]);
            var txt1 = component.find("text1") ;
            $A.util.removeClass(txt1,'toggle1');
            $A.util.addClass(component.find('div2'),'toggle1');
            helper.calculate2(component);
            helper.showmessage1(component);
        }}
})

6. Now add this code to the helper sections

({sendMessage : function(component, event, helper) {
        var msg = {
            name: "General",
            value: "Test"
        };
        component.find("AngularApp").message(msg);
    },
    handleMessage: function(component, message, helper) {
        console.log('message received');
        var payload = message.payload;
        var name = payload.name;
        if (name === "General") {
            var value = payload.value;
            component.set("v.messageReceived", value);
        }
        else if (name === "Foo") {
            // A different response
        }
    },

    showmessage1 : function(component) {
     
        console.log("this is debugging message");
        alert( component.get("v.Maturity"));
    },
 
    validate12: function(component,helper){
         var inputcmp = component.find("tenure");
         var val  =inputcmp.get("v.value");
        console.log(component);
       // console.log(inputcmp.get("v.label"));
        if (val <10){   
        inputcmp.set("v.errors",[{message :'Value cant be less than 10 '}]);
         
        }else{
             inputcmp.set("v.errors",[{message :''}]);
            helper.calculate2(component);
        }
            //add the line to remove class and show error message on text1
     
    },
 
    calculate2 : function(component) {   
     

     
     
     
        var x = component.get("v.Amount");
   
        var y = component.get("v.Tenure");
        var z =0;
        if(y < 12){
            z = x +1000;         
        }
        if(y >12){         
            z = x -1000;
        } 
        component.set("v.Maturity",z);
        console.log(z);
         console.log('inside helper');
     
    }
 
 
})

7. Add this to the style section

.THIS.changeMe {
    background-color:Red;
    width:200px;
    color: blue;
}

.THIS.colorme{
      font: italic bold 12px/30px Georgia, serif;
     color:blue;
}
.THIS.toggle1 {
    display: none;
    visibility:hidden;
}

.THIS.toggle2 {
 
    display: inline;
}

7. Now navigate back to menu and click on new apex class and create new class called
ContactController. This is the backend apex class for the component which is also aura enabled

public with sharing class ContactController {

    @AuraEnabled
    public static String retcontactname(Id id) {
   Contact con = new contact();
        try{
         
         
       con = [SELECT name FROM Contact where id =:id];
   
        }catch(System.Exception  e){
           // system.debug('error');
            return 'error'+e.getmessage();
        }
       return con.name;
    }
    @AuraEnabled
         public static String retaccountdetails(Id id){
     List<account> acc = new List<Account>();
         acc = [Select id,name,billingaddress,(select name from contacts)  from account where id =:id];
         return acc[0].name+';'+acc[0].contacts[0].name;
    } 
     @AuraEnabled
     public static List<Contact> retaccountdetailslist(Id id){
     List<account> acc = new List<Account>();
     List<Contact> con = new List<Contact>(); 
         acc = [Select id,name,billingaddress,(select id, name from contacts)  from account where id =:id];
         for (account ac:acc){ 
             for(contact co:ac.contacts){
            con.add(co);
             }
         }
       
      return con;
    }
 
    }

8 .Now create new lightning application and embed this component you just created,


<aura:application access="GLOBAL" extends="force:slds" >
   <c:TestUIContact /> 
 
</aura:application>


Now hit preview button to see your application:


To learn more in details ,please register for the full detailed salesforce course at
https://www.udemy.com/programming-salesforce-lightning-components-dev-601-salesforce/?instructorPreviewMode=guest





lightning component development,
lightning component development best practices,
lightning component development tutorial,
lightning component development trailhead,
lightning component development day 1,
lightning component development with vscode and sa,
lightning component development with vscode & salesforce,
lightning web component ,



salesforce developer,
salesforce developer salary,
salesforce developer certification,
salesforce developer jobs,
salesforce developer interview questions,
salesforce developer edition,
salesforce developer training,
salesforce developer job description,
salesforce developer resume,
salesforce developer 

No comments:

Post a Comment