Sunday 10 September 2017

Create And Display Account Records Using Lightning Component

What is lightning component

Lightning component is UI framework for developing dynamic web apps for mobile device and desktop device. It uses JavaScript on the client side and Apex on the server side.
The Lightning Component framework is built on the open source Aura framework. The Aura framework enables you to build apps completely independent of your data in Salesforce.




Create lightning component to display accounts record

Step-1
Go to developer console by click on User Menu from setup then in console go to file option than New and then Lightning Component then provide name and description and submit, your component is ready to use.

Now write code to display record-
First, create Apex class and create a static method in a class and this method should have annotation @AuraEnabled so that we can use this method in lightning component framework to get data.

Apex Class

public class AccountAuraClr {
@AuraEnabled
    public static List<Account> getAccountRecord() {
        return new List<Account>([Select id,Name,Phone,Type from Account where Type != null ORDER BY CreatedDate desc LIMIT 100]);
    }
    
    //Create new account records
    @AuraEnabled
    public static void createAccount(Account acc)
    {
        if(acc != null)
            insert acc;
    }
}

Now create lightning component name SalesforceAdda_Account and use this class as a controller in the component.

Lightning Component (SalesforceAdda_Account)

In this component I add 'New' button and click on button it open a popup , fill the information  in popup and click on save button then account record will be created in Account object and close the popup.

<aura:component controller="AccountAuraClr"
                implements="force:appHostable,forceCommunity:availableForAllPageTypes,flexipage:availableForAllPageTypes"
                access="global">
    <aura:attribute name="displayNewAccount" type="Boolean" default="false"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" /> <!-- calling doInit method in Component Controller -->
    <aura:handler event="bappi:NewClosedModalEvent" action="{!c.newClosedModal}"/> <!-- create event for closed modal.-->
    <aura:attribute name="accLst" type="Account[]"/> <!-- create Array type Account variable-->
    <article class="slds-card">
      <div class="slds-card__header slds-grid">
        <header class="slds-media slds-media_center slds-has-flexi-truncate">
          <div class="slds-media__figure">
            <span class="slds-icon_container slds-icon-standard-account" title="description of icon when needed">
                <lightning:icon iconName="standard:account" size="large" alternativeText="List account"/>
            </span>
          </div>
          <div class="slds-media__body">
            <h2>
              <a href="javascript:void(0);" class="slds-card__header-link slds-truncate" title="Account">
                <span class="slds-text-heading_small">Account</span>
              </a>
            </h2>
          </div>
        </header>
        <div class="slds-no-flex">
          <lightning:button label="New" onclick="{!c.showAccountModal}"/>
        </div>
      </div>
      <div class="slds-card__body">
        <table class="slds-table slds-table_bordered slds-no-row-hover slds-table_cell-buffer">
          <thead>
            <tr class="slds-text-title_caps">
              <th scope="col">
                <div class="slds-truncate" title="Name">Name</div>
              </th>
              <th scope="col">
                <div class="slds-truncate" title="Type">Type</div>
              </th>
              <th scope="col">
                <div class="slds-truncate" title="Phone">Phone</div>
              </th>
            </tr>
          </thead>
          <tbody>
              <aura:iteration items="{!v.accLst}" var="acc"> <!-- iteration account record.-->
                  <tr class="slds-hint-parent">
                      <th scope="row">
                          <div class="slds-truncate" title="Adam Choi"><a href="javascript:void(0);">{!acc.Name}</a></div>
                      </th>
                      <td>
                          <div class="slds-truncate" title="Company One">{!acc.Type}</div>
                      </td>
                      <td>
                          <div class="slds-truncate" title="{!acc.Phone}">{!acc.Phone}</div>
                      </td>
                  </tr>                     
              </aura:iteration>
          </tbody>
        </table>
      </div>
      <footer class="slds-card__footer"><a href="javascript:void(0);"></a></footer>
    </article>
   <aura:if isTrue="{!v.displayNewAccount}">
        <c:Salesforceadda_NewAccount /> <!-- this is another component and contains popup and there fields to save account info -->
    </aura:if>
 </aura:component>

Now create another Salesforceadda_NewAccount

Lightning Component (Salesforceadda_NewAccount) --


<aura:component implements="force:appHostable" access="global" controller="AccountAuraClr" >
     <!--Start Modal New Account -->
    <aura:attribute name="accObj" type="Account"  default="{'sobjectType': 'Account',
                         'Name': '',
                         'Type': '',
                         'Phone': ''                               
                       }"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <div class="demo-only" style="height: 640px;">
      <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-describedby="modal-content-id-1" class="slds-modal slds-fade-in-open">
        <div class="slds-modal__container">
          <header class="slds-modal__header">
            <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">Create Account</h2>
            <p class="slds-m-top_x-small"> <a href="javascript:void(0);"></a>.</p>
          </header>
          <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
           <div class="slds-form-element">
              <div class="slds-form-element__control">
                  <lightning:input type="Text" label="Name" name="Accountname" value="{!v.accObj.Name}" />
              </div>
            </div>
            <div class="slds-form-element">
              <div class="slds-form-element__control">
                  <lightning:select name="selectItem" label="Type" value="{!v.accObj.Type}" >
                        <option value="Customer - Direct">Customer - Direct</option>
                        <option value="Prospect">Prospect</option>
                  </lightning:select>
              </div>
            </div>
            <div class="slds-form-element">
              <div class="slds-form-element__control">
                  <lightning:input type="tel" label="Phone"  name="tel" value="{!v.accObj.Phone}" />
              </div>
            </div>
          </div>
          <footer class="slds-modal__footer">
            <lightning:button label="Cancel" onclick="{!c.closedModal}"/>
                                    <lightning:button label="Save" onclick="{!c.saveAccount}"/>
          </footer>
        </div>
      </section>
      <div class="slds-backdrop slds-backdrop_open"></div>
    </div>
    <!--End Modal New Account -->
</aura:component>

So this lightning component will open in popup of account creation two buttons are there are Save and Cancel.

Onclick on Save button , an action is called from lightning component controller (Salesforceadda_NewAccountController.jsand from there we call Apex class method to save the data.

Now create Lightning Component Controller:

Lightning Component Controller (Salesforceadda_NewAccountController.js)--


({
closedModal: function(component,event,helper){
       helper.closedModal();         
    },
    saveAccount : function(component,event,helper){
       //getting the candidate information
        var accountRecord = component.get("v.accObj");
        //Calling the Apex Function
        var action = component.get("c.createAccount");
        
        //Setting the Apex Parameter
        action.setParams({
            acc : accountRecord
        });
        
        //Setting the Callback
        action.setCallback(this,function(a){
            //get the response state
            var state = a.getState();
            
            //check if result is successfull
            if(state == "SUCCESS"){
                //Reset Form
                var newAccount = {'sobjectType': 'Account',
                                    'Name': '',
                                    'Type': 'Customer - Direct',
                                    'Phone': ''
                                   };
                
                //resetting the Values in the form
                component.set("v.accObj",newAccount);
            
           else if(state == "ERROR"){
                alert('Error in calling server side action');
            }
        });
//adds the server-side action to the queue        
        $A.enqueueAction(action);
        helper.closedModal(); //calls helper controller method to close the popup and refresh the account list. 
    }
})

Now Create Lightning component helper , in this we define closedModal() method.

Lightning Component Helper  (Salesforceadda_NewAccountHelper.js) -->


({
closedModal : function() {
        var appEvent = $A.get("e.bappi:NewClosedModalEvent"); // Here 'bappi' is my org namespace, If you do not have namespace then you can write 'e:NewClosedModalEvent'
        appEvent.setParams(false);
        appEvent.fire();
}
})


Now Create Lightning Event (NewClosedModalEvent) which is using in these components: 

Lightning Event (NewClosedModalEvent)

<aura:event type="APPLICATION" description="closed modal " >
    <aura:attribute name="closedModal" type="boolean" />
</aura:event>

So we have completed the New button popup component functionality, Now go to previous component SalesforceAdda_Account and to display accounts records and close model.

Now create lightning component controller (SalesforceAdda_AccountController) for SalesforceAdda_Account component to display records on load, open popup on New button and rerender record after save the record from popup.  by click on controller link in lightning component right-hand side. After click it will automatically name SalesforceAdda_AccountController.js

Lightning Component Controller (SalesforceAdda_AccountController

use this code in your controller.

({
doInit : function(component, event, helper) {
helper.getAccontRecord(component); // Calling Helper method on load
},
    showAccountModal : function(component,event,helper){
        component.set("v.displayNewAccount",true); // calls to show popup
    },
    newClosedModal:function(component,event,helper){
        component.set("v.displayNewAccount",false);
        helper.getAccontRecord(component); // Calling Helper method to display record after record save from popup
    }
})

Now create helper for component where we write JavaScript Code to call class method to get data.

Lightning Component Helper

({
getAccontRecord : function( component ) {
var action = component.get("c.getAccountRecord"); //Calling Apex class controller 'getAccountRecord' method
        action.setCallback(this, function(response) {
            var state = response.getState(); //Checking response status
            var result = JSON.stringify(response.getReturnValue());
            if (component.isValid() && state === "SUCCESS")
                component.set("v.accLst", response.getReturnValue());  // Adding values in Aura attribute variable.   
        });
        $A.enqueueAction(action);
},
})

Use this code into your org to display records.

After creating component successfully, how you will preview component, to preview component you have to create Lightning Application.

How To Preview Lightning Component?

       1.  In developer console, go to file then select new then click on Lightning Application option to create App.
       2.  Reference your lightning component in application like-
                         <c:SalesforceAdda_Account />

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

Now click on Preview button in lightning app in right hand side.

Note: You can use this component in your salesforce community, lightning app builder etc.

How to use lightning component in community,builder,app etc?

Add implements attribute and provide values in this like-

<aura:component controller="AccountAuraClr" implements="force:appHostable,forceCommunity:availableForAllPageTypes,flexipage:availableForAllPageTypes" access="global">

19 comments:

  1. Replies
    1. This page has an error. You might just need to refresh it.
      Unable to find 'doInit' on 'compound://c.Salesforceadda_NewAccount'.
      Failing descriptor: {markup://c:Salesforceadda_NewAccount}

      the doInIt function is not defined in Salesforceadda_NewAccount. When added as a component tab, the 'New' button itself doesnt work.(the above error shows while previewing). Please check. thanks

      Delete
    2. If i remove that 1 line, its working. Thanks.

      Delete
  2. cant make it to work error on SalesforceADDA_Account.cmp I cant save it

    ReplyDelete
    Replies
    1. "bappi:" is namespace of my org you just remove this text and repalce by "c:" or if you have your org namespace so please replace with your name space.
      This is event "NewClosedModalEvent" and you should create event with name.

      Delete
  3. Failed to save SalesforceAdda_Account.cmp: No EVENT named markup://bappi:NewClosedModalEvent found : [markup://c:SalesforceAdda_Account]: Source

    ReplyDelete
    Replies
    1. "bappi:" is namespace of my org you just remove this text and repalce by "c:" or if you have your org namespace so please replace with your name space.
      This is event "NewClosedModalEvent" and you should create event with name.

      Delete
  4. Great article. Brother, I am unable to create new Account

    ReplyDelete
  5. Unable to create new Account

    ReplyDelete
    Replies
    1. All component has been saved successfully? If you are not able to save account can you tell me what is the error? If not you can mail me I will guide you personally.

      Delete
  6. I have error new account button dont work. This is a error:

    This page has an error. You might just need to refresh it.
    Unable to find 'doInit' on 'compound://c.Salesforceadda_NewAccount'.
    Failing descriptor: {markup://c:Salesforceadda_NewAccount}

    Salesforceadda_NewAccount Controller dont have a doinit function

    Please Help me

    ReplyDelete
    Replies
    1. Did you create doInit function in controller or if you have created then did you define in your component?

      Delete
  7. modal is not closing and not throwing any error

    ReplyDelete
    Replies
    1. did you check function by putting alert when close modal. Please check first that modal close click function is calling or not. If not please let me know with full code then I will tell you.

      Delete
  8. I want the search bar in it.............

    ReplyDelete
  9. Do we have similar type code for contact screen

    ReplyDelete
  10. Failed to save salesforceaddaaccount component.it shows No component named markup://c:salesforceadda_newaccount found:source.. Plz help me

    ReplyDelete

If you have any doubts, please let me know.