Thursday, 22 March 2018

Adding New contact to table dynamically and process selected contacts through check boxes in Lightning

Hi ,

Here we are going to learn how to save Record and then added to list which are displaying in the component on load.

In the table you can see check boxes for selecting multiple records and then process selected records.


Wrapper Class: Which holds Contact object and isSelected boolean variables to combine checkbox with contact record.

public class ContactWrapper{
        @Auraenabled
        public Contact contactObj;
        @Auraenabled
        public boolean isSelected;
}

Apex Class (Controller):

public class ContactCls {
  //retrieving contacts and return to the lightning component
    @Auraenabled
    public  static List<ContactWrapper> retrieveContacts(){
        List<ContactWrapper> contactWrapperList = new List<ContactWrapper>();
        for(Contact contactObj:[select id,firstName,LastName from Contact where firstName!=null order by createddate desc limit 6]){
            ContactWrapper contactWrapObj = new ContactWrapper();
            contactWrapObj.contactObj = contactObj;
            contactWrapObj.isSelected = false;
            contactWrapperList.add(contactWrapObj);
        }
        return contactWrapperList;
    }

//for sending contacts when we click on "Process Contacts" button along with checkbox selection
    @Auraenabled
    public static String updateContacts(String contactString){
        String ids = '';
        List<ContactWrapper> contactWrapList = (List<ContactWrapper>)JSON.deserialize(contactString, List<ContactWrapper>.class);
        for(ContactWrapper contacctWrapObj:contactWrapList){
            if(contacctWrapObj.isSelected){
                ids+=contacctWrapObj.contactObj.Id;
            }
        }
        return ids;
    }

//For saving contact record and returning the wrapper record to lightning component
    @Auraenabled
    public static ContactWrapper saveContact(Contact contObj){
        ContactWrapper contWrapperObj = new ContactWrapper();
        insert contObj;
        if(contObj.Id!=null){
            contWrapperObj.contactObj = contObj;
            contWrapperObj.isSelected = false;
        }
       
        return contWrapperObj;
    }

}



Lightning Component: Contact_Componen.cmp
-------------------------
<aura:component controller="ContactCls">
    <aura:attribute name="contObj" type="Contact" default="{'sobjectType':'Contact',
                                                             'FirstName':'',
                                                             'LastName':''}"/>
    <aura:attribute name="contactList" type="ContactWrapper[]"/>   
    <aura:handler name="init" value="{!this}" action="{!c.myAction}"/> 
    <div class="slds-card">
         <div class="slds-card__header slds-grid">
             <div class="slds-media__body">
        <span class="slds-text-heading_small">Save Contact and Add it to table with checkbox selection</span>
              </div>
        </div>
        <div class="slds-card__body slds-card__body_inner">
             <ui:inputText class="slds-input" label="First Name" value="{!v.contObj.FirstName}"/><br/>
             <ui:inputText class="slds-input" label="Last Name" value="{!v.contObj.LastName}"/><br/>
            <ui:button class="slds-button" press="{!c.contactSave}">Save</ui:button>
        </div>
    </div>
    <br/>
    <div class="slds-card">
         <div class="slds-card__body slds-card__body_inner">
<table class="slds-table slds-table_bordered slds-table_cell-buffer">
        <thead>
            <tr class="slds-text-title_caps">
                <th scope="col">
                    <div class="slds-truncate">Select</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="First Name">First Name</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Last Name">Last Name</div>
                </th>               
            </tr>
        </thead> 
        <tbody>
        <aura:iteration items="{!v.contactList}" var="contactWrap" indexVar="index">
                <tr class="slds-text-title_caps">
                        <td>
                           <ui:inputCheckbox value="{!contactWrap.isSelected}"/>
                        </td>                                             
               
                        <td>
                            <ui:outputText value="{!contactWrap.contactObj.FirstName}"/>
                        </td>
                        <td>
                            <ui:outputText value="{!contactWrap.contactObj.LastName}"/>
                        </td>                                             
                </tr>
            </aura:iteration>
       
        </tbody>
    </table>
   
    <br/>
    <ui:button class="slds-button" press="{!c.updateSelectedContacts}">Process Contacts</ui:button>
        </div>
  </div>
</aura:component>

Controller: Conact_ComponentController.js
({
//for displaying contacts
     myAction : function(component, event, helper) {       
var action = component.get("c.retrieveContacts");
        action.setCallback(this,function(data){
            var result = data.getReturnValue();
            component.set("v.contactList",result);
        });
        $A.enqueueAction(action);
},
 //for processing selected contacts
    updateSelectedContacts : function(component,event,helper){
       var contactList = component.get("v.contactList");
       var action = component.get("c.updateContacts");
        action.setParams({"contactString":JSON.stringify(contactList)});
        action.setCallback(this,function(data){
            var result = data.getReturnValue();
            alert(result);
        });
        $A.enqueueAction(action);     
    },
  //for saving a contact and adding the same into list at 0th index by using "splice" method
    contactSave : function(component,event,helper){
        var contactObj = component.get("v.contObj");
        var contactsList = component.get("v.contactList");
        var action = component.get("c.saveContact");
        action.setParams({"contObj":contactObj});
        action.setCallback(this,function(data){
            var result = data.getReturnValue();         
            contactsList.splice(0,0,result);           
            component.set("v.contactList",contactsList);         
        })
        $A.enqueueAction(action);
    }
})


Lightning App: Contact_ComponentApp.app
---------------------
<aura:application implements="force:appHostable" extends="force:slds">
    <c:Conact_Component />
</aura:application>




Output:
----------



References:

https://www.w3schools.com/jsref/jsref_splice.asp (for splice method in javascript)
https://www.lightningdesignsystem.com/components/cards/
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/aura_compref_ui_inputCheckbox.htm
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/apex_records_save.htm




1 comment:

  1. hi your blog Article is very nice & thanks for sharing the information.salesforce training

    ReplyDelete

What’s the difference between Einstein Article Recommendations and Suggested Articles?

How Does Einstein Article Recommendations Work? Einstein Article Recommendations helps support agents resolve customer cases efficiently by ...