+ Start a Discussion
muneeswar umuneeswar u 

Lightning component with checkboxes to update contact record

Lightning component to update contact record with checkbox field=true
Hi all,
I am new to coding.I am stuck here can any one please help me.Your help is appreciated.

My requirement is to display 10 contact records with checkbox beside to it , with update button at last.After clicking on the update button ,selected record should get updated.
Below is my code

***************************APEX CODE***********************************
public class getAllContactRecords 
{
    @AuraEnabled
    public static List<contactListWrapper> getContacts()
    {
        List<contactListWrapper> lstContactWrap=new List<contactListWrapper>();
        for(Contact con:[select id,Name from Contact limit 10])
        {
            lstContactWrap.add(new contactListWrapper(false,con));
        }
        return lstContactWrap;
    }
    
    /* wrapper class */  
    public class contactListWrapper 
    {
        @AuraEnabled public boolean isChecked ;
        @AuraEnabled public  contact objContact ;
        public contactListWrapper(boolean isChecked, contact objContact)
        {
            this.isChecked = isChecked;
            this.objContact = objContact;
        }
    }
    
}

***************************Lightning component***********************************
<aura:component controller="getAllContactRecords" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
   <!-- aura attributes to store data/values --> 
    <aura:attribute name="ContactList" type="Contact[]"/>
    <!-- call doInit method on component load -->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <aura:iteration items="{!v.ContactList}" var="obj">
        
        <tr>
            <td>  <ui:inputCheckbox text="{!obj.objContact.Id}"
                                    value="{!obj.isChecked}"
                                    change="{!c.checkboxSelect}" aura:id="chkBoxId"/>
            </td>
            <td>
                {!obj.objContact.Name} <br/> 
            </td>
        </tr>

    </aura:iteration>
    
    <lightning:button label="Update" onclick="{!c.updateSelectedRecords}"/> 
</aura:component>

***************************Lightning controller***********************************

({
    doInit : function(component, event, helper) 
    {
        var action=component.get("c.getContacts");
        action.setCallback(this, function(data){
            
            component.set("v.ContactList",data.getReturnValue());
            
        });  
        $A.enqueueAction(action);
    },
    
    
    checkboxSelect : function(component, event, helper) 
    {
         alert('test');
        var selectedHeaderCheck = event.getSource().get("v.text");
        var checkVar=component.find("v.chkBoxId");
        alert(selectedHeaderCheck);
     //  $A.enqueueAction(action);
    },
    
    updateSelectedRecords : function(component, event, helper) 
    {
        alert('test 1')
       var check=component.find("v.chkBoxId");
         if (check.get("v.value") == true)
         {
          //         updateId.push(getAllId.get("v.text"));
         }
      // $A.enqueueAction(action); 
    } 
})
Best Answer chosen by muneeswar u
Khan AnasKhan Anas (Salesforce Developers) 
Hi Muneeswar,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Apex:
public class UpdateUsingCheckboxC {
    
    @AuraEnabled
    public static List <Contact> fetchContact() {
        return [SELECT Id, FirstName, LastName, Phone FROM Contact Limit 10];
    }
    
    @AuraEnabled
    public static void updateRecord(List <String> lstRecordId) {
        List<Contact> lstUpdate = new List<Contact>();
        for(Contact con : [SELECT Id, FirstName, LastName, Phone FROM Contact WHERE Id IN : lstRecordId]){
            con.Phone = '999999'; // Add fields which you want to update
            lstUpdate.add(con);
        }
        
        if(lstUpdate.size() > 0){
            update lstUpdate;
        }
        
    }
}

Component:
<aura:component controller="UpdateUsingCheckboxC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <aura:attribute name="ContactList" type="List" />
    
    <aura:handler name="init" value="{!this}" action="{!c.loadContacts}"/>
    <aura:handler event="force:refreshView" action="{!c.loadContacts}" />
    
    <div class="slds-grid slds-grid--align-end"> 
        <button class="slds-button slds-button--brand" onclick="{!c.updateFields}">Update</button>
    </div>
    
    
    <table class="slds-table slds-table--bordered slds-table--cell-buffer">
        <thead>
            <tr class="slds-text-title--caps">
                <th style="width:3.25rem;" class="slds-text-align--right">
                    <div class="slds-form-element">
                        <div class="slds-form-element__control">
                            <label class="slds-checkbox">
                                <!--header checkbox for select all-->
                                <ui:inputCheckbox aura:id="box3" change="{!c.selectAll}"/>
                                <span class="slds-checkbox--faux"></span>
                                <span class="slds-form-element__label text"></span>
                            </label>
                        </div>
                    </div>
                </th>
                <th>
                    <span class="slds-truncate">FirstName</span>      
                </th>
                <th>
                    <span class="slds-truncate">LastName</span>
                </th>
                <th>       
                    <span class="slds-truncate">Phone</span>
                </th>
            </tr>
        </thead>
        
        <tbody>
            <aura:iteration items="{!v.ContactList}" var="con">
                <tr>
                    <td scope="row" class="slds-text-align--right" style="width:3.25rem;">
                        <div class="slds-form-element">
                            <div class="slds-form-element__control">
                                <label class="slds-checkbox">
                                    <ui:inputCheckbox text="{!con.Id}" aura:id="boxPack" value=""/>
                                    <span class="slds-checkbox--faux"></span>
                                    <span class="slds-form-element__label text"></span>
                                </label>
                            </div>
                        </div>
                    </td>
                    <td scope="row">
                        <div class="slds-truncate" title="{!con.FirstName}"><a>{!con.FirstName}</a></div>
                    </td>
                    <td scope="row">
                        <div class="slds-truncate" title="{!con.LastName}">{!con.LastName}</div>
                    </td>
                    <td scope="row">
                        <div class="slds-truncate" title="{!con.Phone}">{!con.Phone}</div>
                    </td>
                </tr>
            </aura:iteration>
        </tbody>
    </table>
</aura:component>

Controller:
({
    loadContacts: function(component, event, helper) {
        var action = component.get('c.fetchContact');
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set('v.ContactList', response.getReturnValue());
                component.find("box3").set("v.value", false);
            }
        });
        $A.enqueueAction(action);
    },
    
    selectAll: function(component, event, helper) {
        var selectedHeaderCheck = event.getSource().get("v.value");
        var getAllId = component.find("boxPack"); 
        if(! Array.isArray(getAllId)){
            if(selectedHeaderCheck == true){ 
                component.find("boxPack").set("v.value", true);    
            }else{
                component.find("boxPack").set("v.value", false);
            }
        }else{
            // check if select all (header checkbox) is true then true all checkboxes on table in a for loop  
            // and set the all selected checkbox length in selectedCount attribute.
            // if value is false then make all checkboxes false in else part with play for loop 
            // and select count as 0
            if (selectedHeaderCheck == true) {
                for (var i = 0; i < getAllId.length; i++) {
                    component.find("boxPack")[i].set("v.value", true);
                }
            } else {
                for (var i = 0; i < getAllId.length; i++) {
                    component.find("boxPack")[i].set("v.value", false);
                }
            } 
        }  
    },
    
    updateFields: function(component, event, helper) {
        var updateId = [];
        var getAllId = component.find("boxPack");
        
        if(! Array.isArray(getAllId)){
            if (getAllId.get("v.value") == true) {
                updateId.push(getAllId.get("v.text"));
            }
        }else{
            
            for (var i = 0; i < getAllId.length; i++) {
                if (getAllId[i].get("v.value") == true) {
                    updateId.push(getAllId[i].get("v.text"));
                }
            }
        } 
        
        var action = component.get('c.updateRecord');
        action.setParams({
            "lstRecordId": updateId
        });
        action.setCallback(this, function(response) {
            
            var state = response.getState();
            if (state === "SUCCESS") {
                console.log(state);
                $A.get('e.force:refreshView').fire();
            }
        });
        $A.enqueueAction(action);
    },
    
})

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

Reference: http://sfdcmonkey.com/2017/02/23/delete-multiple-records-using-checkbox-lightning-component/

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas​​​​​​​

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi Muneeswar,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Apex:
public class UpdateUsingCheckboxC {
    
    @AuraEnabled
    public static List <Contact> fetchContact() {
        return [SELECT Id, FirstName, LastName, Phone FROM Contact Limit 10];
    }
    
    @AuraEnabled
    public static void updateRecord(List <String> lstRecordId) {
        List<Contact> lstUpdate = new List<Contact>();
        for(Contact con : [SELECT Id, FirstName, LastName, Phone FROM Contact WHERE Id IN : lstRecordId]){
            con.Phone = '999999'; // Add fields which you want to update
            lstUpdate.add(con);
        }
        
        if(lstUpdate.size() > 0){
            update lstUpdate;
        }
        
    }
}

Component:
<aura:component controller="UpdateUsingCheckboxC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <aura:attribute name="ContactList" type="List" />
    
    <aura:handler name="init" value="{!this}" action="{!c.loadContacts}"/>
    <aura:handler event="force:refreshView" action="{!c.loadContacts}" />
    
    <div class="slds-grid slds-grid--align-end"> 
        <button class="slds-button slds-button--brand" onclick="{!c.updateFields}">Update</button>
    </div>
    
    
    <table class="slds-table slds-table--bordered slds-table--cell-buffer">
        <thead>
            <tr class="slds-text-title--caps">
                <th style="width:3.25rem;" class="slds-text-align--right">
                    <div class="slds-form-element">
                        <div class="slds-form-element__control">
                            <label class="slds-checkbox">
                                <!--header checkbox for select all-->
                                <ui:inputCheckbox aura:id="box3" change="{!c.selectAll}"/>
                                <span class="slds-checkbox--faux"></span>
                                <span class="slds-form-element__label text"></span>
                            </label>
                        </div>
                    </div>
                </th>
                <th>
                    <span class="slds-truncate">FirstName</span>      
                </th>
                <th>
                    <span class="slds-truncate">LastName</span>
                </th>
                <th>       
                    <span class="slds-truncate">Phone</span>
                </th>
            </tr>
        </thead>
        
        <tbody>
            <aura:iteration items="{!v.ContactList}" var="con">
                <tr>
                    <td scope="row" class="slds-text-align--right" style="width:3.25rem;">
                        <div class="slds-form-element">
                            <div class="slds-form-element__control">
                                <label class="slds-checkbox">
                                    <ui:inputCheckbox text="{!con.Id}" aura:id="boxPack" value=""/>
                                    <span class="slds-checkbox--faux"></span>
                                    <span class="slds-form-element__label text"></span>
                                </label>
                            </div>
                        </div>
                    </td>
                    <td scope="row">
                        <div class="slds-truncate" title="{!con.FirstName}"><a>{!con.FirstName}</a></div>
                    </td>
                    <td scope="row">
                        <div class="slds-truncate" title="{!con.LastName}">{!con.LastName}</div>
                    </td>
                    <td scope="row">
                        <div class="slds-truncate" title="{!con.Phone}">{!con.Phone}</div>
                    </td>
                </tr>
            </aura:iteration>
        </tbody>
    </table>
</aura:component>

Controller:
({
    loadContacts: function(component, event, helper) {
        var action = component.get('c.fetchContact');
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set('v.ContactList', response.getReturnValue());
                component.find("box3").set("v.value", false);
            }
        });
        $A.enqueueAction(action);
    },
    
    selectAll: function(component, event, helper) {
        var selectedHeaderCheck = event.getSource().get("v.value");
        var getAllId = component.find("boxPack"); 
        if(! Array.isArray(getAllId)){
            if(selectedHeaderCheck == true){ 
                component.find("boxPack").set("v.value", true);    
            }else{
                component.find("boxPack").set("v.value", false);
            }
        }else{
            // check if select all (header checkbox) is true then true all checkboxes on table in a for loop  
            // and set the all selected checkbox length in selectedCount attribute.
            // if value is false then make all checkboxes false in else part with play for loop 
            // and select count as 0
            if (selectedHeaderCheck == true) {
                for (var i = 0; i < getAllId.length; i++) {
                    component.find("boxPack")[i].set("v.value", true);
                }
            } else {
                for (var i = 0; i < getAllId.length; i++) {
                    component.find("boxPack")[i].set("v.value", false);
                }
            } 
        }  
    },
    
    updateFields: function(component, event, helper) {
        var updateId = [];
        var getAllId = component.find("boxPack");
        
        if(! Array.isArray(getAllId)){
            if (getAllId.get("v.value") == true) {
                updateId.push(getAllId.get("v.text"));
            }
        }else{
            
            for (var i = 0; i < getAllId.length; i++) {
                if (getAllId[i].get("v.value") == true) {
                    updateId.push(getAllId[i].get("v.text"));
                }
            }
        } 
        
        var action = component.get('c.updateRecord');
        action.setParams({
            "lstRecordId": updateId
        });
        action.setCallback(this, function(response) {
            
            var state = response.getState();
            if (state === "SUCCESS") {
                console.log(state);
                $A.get('e.force:refreshView').fire();
            }
        });
        $A.enqueueAction(action);
    },
    
})

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

Reference: http://sfdcmonkey.com/2017/02/23/delete-multiple-records-using-checkbox-lightning-component/

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas​​​​​​​
This was selected as the best answer
muneeswar umuneeswar u
Thank you Anas
Renuka SharmaRenuka Sharma
Hello Guys

i am also work on the same requirement

I am working on a Education project, I have four custom objects, Student__c, Class__c, course__c,Attandence__c
The first part is working fine,  That is, (Snapshot 1)  when I click on Update Attendance button, a check box is checked in a student object (Snapshot 2) and it Is also checked in child object called Attendance__c and Related Record Gets created (Snapshot 3)
Now I want to put another button called as Update Absentee, when I click this button, Checkbox should get updated in the Student object named (Check for Absentee__c) and related record should get created and it should not get updated in attendance custom object,

Can anyone please help regarding this issue
Updateusingcheckbox.apex

public class UpdateUsingCheckboxC {
    
    @AuraEnabled
    public static List <Contact> fetchContact(string key) {
        system.debug('classname'+key);
        Class__c cls = [select id,Courses__r.name from Class__c where id=:key];
        string classname = cls.Courses__r.name;
        system.debug('classname'+classname);
        return [SELECT Id, Name,Account.Name,FirstName,LastName,Check_for_Attendance__c FROM Contact where Check_for_Attendance__c=false AND Account.Name =:classname];
    }
    
    @AuraEnabled
    public static void updateRecord(List <String> lstRecordId,string key) {
        List<Contact> lstUpdate = new List<Contact>();
        List<Attendancess__c> listAttendnce = new List<Attendancess__c>();
        Class__c cls = [select id,Courses__r.name from Class__c where id=:key];
        for(Contact con : [SELECT Id,AccountId, Name,Phone,FirstName,LastName,Check_for_Attendance__c  FROM Contact WHERE Id IN : lstRecordId]){
            con.Check_for_Attendance__c = true;
            lstUpdate.add(con);   
            Attendancess__c attandenc = new Attendancess__c();
            attandenc.Class__c = cls.Id;
            attandenc.Student_Attended__c = true;
            attandenc.Name = con.Name;
            attandenc.Created_Date_Time__c = system.now();
            listAttendnce.add(attandenc);
            system.debug('listAttendnce'+listAttendnce);
        }
        if(lstUpdate.size() > 0){
            update lstUpdate;
        }
        if(listAttendnce.size() > 0){
            insert listAttendnce;
        }
    }
}

ManjuDisplayContacts.cmp
<aura:component controller="UpdateUsingCheckboxC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <aura:attribute name="ContactList" type="List" />
    <aura:handler name="init" value="{!this}" action="{!c.loadContacts}"/>
    <aura:handler event="force:refreshView" action="{!c.loadContacts}" />
    <div class="slds-grid slds-grid--align-end"> 
        <button class="slds-button slds-button--brand" onclick="{!c.updateFields}">Update Attendance</button>
    </div>
    <table class="slds-table slds-table--bordered slds-table--cell-buffer">
        <thead>
            <tr class="slds-text-title--caps">
                <th></th>
                <th></th>
                <th>
                    <span class="slds-truncate">Attendee</span>      
                </th>
                <th style="width:3.25rem;" class="slds-text-align--right">
                    <div class="slds-form-element">
                        <div class="slds-form-element__control">
                            <label class="slds-checkbox">
                                <!--header checkbox for select all-->
                                <ui:inputCheckbox aura:id="box3" change="{!c.selectAll}"/>
                                <span >Attended</span>
                                <span class="slds-form-element__label text"></span>
                            </label>
                        </div>
                    </div>
                </th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <aura:iteration items="{!v.ContactList}" var="con">
                <tr>
                    <td></td>
                    <td></td>
                    <td scope="row">
                        <div class="slds-truncate" title="{!con.Name}"><a>{!con.Name}</a></div>
                    </td>
                    
                    
                    <td scope="row" class="slds-text-align--right" style="width:3.25rem;">
                        <div class="slds-form-element">
                            <div class="slds-form-element__control">
                                <label class="slds-checkbox">
                                    <ui:inputCheckbox text="{!con.Id}" aura:id="boxPack" value=""/>
                                    <span class="slds-checkbox--faux"></span>
                                    <span class="slds-form-element__label text"></span>
                                </label>
                            </div>
                        </div>
                    </td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                </tr>
            </aura:iteration>
        </tbody>
    </table>
</aura:component>
ManjuDisplayContactsController.js

({
    loadContacts: function(component, event, helper) {
        var rid = component.get("v.recordId");
        var action = component.get('c.fetchContact');
        action.setParams({key : rid});
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set('v.ContactList', response.getReturnValue());
                component.find("box3").set("v.value", false);
            }
        });
        $A.enqueueAction(action);
    },
    selectAll: function(component, event, helper) {
        var selectedHeaderCheck = event.getSource().get("v.value");
        var getAllId = component.find("boxPack"); 
        if(! Array.isArray(getAllId)){
            if(selectedHeaderCheck == true){ 
                component.find("boxPack").set("v.value", true);    
            }else{
                component.find("boxPack").set("v.value", false);
            }
        }else{
            // check if select all (header checkbox) is true then true all checkboxes on table in a for loop  
            // and set the all selected checkbox length in selectedCount attribute.
            // if value is false then make all checkboxes false in else part with play for loop 
            // and select count as 0
            if (selectedHeaderCheck == true) {
                for (var i = 0; i < getAllId.length; i++) {
                    component.find("boxPack")[i].set("v.value", true);
                }
            } else {
                for (var i = 0; i < getAllId.length; i++) {
                    component.find("boxPack")[i].set("v.value", false);
                }
            } 
        }  
    },
   updateFields: function(component, event, helper) {
        var updateId = [];
        var getAllId = component.find("boxPack");
         if(! Array.isArray(getAllId)){
            if (getAllId.get("v.value") == true) {
                updateId.push(getAllId.get("v.text"));
            }
        }else{
            for (var i = 0; i < getAllId.length; i++) {
                if (getAllId[i].get("v.value") == true) {
                    updateId.push(getAllId[i].get("v.text"));
                }
            }
        } 
        var rid = component.get("v.recordId");
        var action = component.get('c.updateRecord');
        action.setParams({
            "lstRecordId": updateId,
            "key" : rid
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                console.log(state);
                $A.get('e.force:refreshView').fire();
            }
        });
        $A.enqueueAction(action);
    },
})


Snapshot1

Snapshot 2
Snapshot 3

Can anyone please Help??