
Delete Multiple Records Using Checkbox In Lightning Component
Delete Multiple Records Using Checkbox
In this post we are seeing that how to delete multiple records using checkbox in salesforce lightning components. also, showing error alert message, if any record dependent to other records.
Prerequisites : basic understanding of Lightning Component. And apex Programming.
Step 1 : Create Server Side Apex Controller.
DeleteWithCheckboxController.apxc
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
public with sharing class DeleteWithCheckboxController { @AuraEnabled public static list < contact > fetchContact() { list < contact > returnConList = new List < contact > (); List < contact > lstCon = [SELECT Name, firstName, LastName, Department, MobilePhone From contact LIMIT 50]; // play for loop on lstCon and add each contact to returnConList List. for (contact c: lstCon) { returnConList.add(c); } // return the List of contacts return returnConList; } @AuraEnabled public static List < String > deleteRecords(List < String > lstRecordId) { // for store Error Messages List < String > oErrorMsg = new List < String > (); // Query Records for delete where id in lstRecordId [which is pass from client side controller] List < contact > lstDeleteRec = [select Id from contact where id IN: lstRecordId]; // delte contact list with Database.DeleteResult[] database class. // It deletes some queried contacts using <samp class="codeph apex_code">Database.<span class="statement">delete</span></samp> // with a false second parameter to allow partial processing of records on failure. // Next, it iterates through the results to determine whether the operation was successful or not // for each record. and check if delete contact successful so print msg on debug, // else add error message to oErrorMsg List and return the list Database.DeleteResult[] DR_Dels = Database.delete(lstDeleteRec, false); // Iterate through each returned result for (Database.DeleteResult dr: DR_Dels) { if (dr.isSuccess()) { system.debug('successful delete contact'); // Operation was successful } else { // Operation failed, so get all errors oErrorMsg.add(''); for (Database.Error err: dr.getErrors()) { // add Error message to oErrorMsg list and return the list oErrorMsg.add(err.getStatusCode() + ': ' + err.getMessage()); } } } return oErrorMsg; } } |
- For this post i have use standard contact object.
- See code comments.
Step 2 : Create Custom Lightning Component.
DeleteWithCheckboxComponent.cmp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
<aura:component controller="DeleteWithCheckboxController" implements="flexipage:availableForAllPageTypes"> <!--Declare Attributes--> <aura:attribute name="ListOfContact" type="contact[]" /> <aura:attribute name="selectedCount" type="integer" default="0"/> <!--aura init handler , call js "loadContactList" function on component load, and display contact data on table--> <aura:handler name="init" value="{!this}" action="{!c.loadContactList}"/> <!--Header part--> <div class="slds-page-header"> <p class="slds-page-header__title slds-truncate" title="">Contact List With Checkbox Action</p> <span class="slds-badge">Selected Contact:{!v.selectedCount}</span> <div class="slds-grid slds-grid--align-end"> <button class="slds-button slds-button--brand" onclick="{!c.deleteSelected}">Delete Contact</button> </div> </div> <!--contacts table part--> <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" title="Name">First Name</span> </th> <th> <span class="slds-truncate" title="Last Name">Last Name</span> </th> <th> <span class="slds-truncate" title="Department">Department</span> </th> <th > <div class="slds-truncate" title="MobilePhone">Mobile Phone</div> </th> </tr> </thead> <!--table body start, Iterate contact list as a <tr> --> <tbody> <aura:iteration items="{!v.ListOfContact}" 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="" change="{!c.checkboxSelect}"/> <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.Name}"><a>{!con.Name}</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.Department}">{!con.Department}</div> </td> <td scope="row"> <div class="slds-truncate" title="{!con.MobilePhone}">{!con.MobilePhone}</div> </td> </tr> </aura:iteration> </tbody> </table> </aura:component> |
- In the above component code, we iterate all contact record with checkbox and store the record id in ui:inputCheckbox text attribute on line number 58 [text=”{!con.id}”} ].
- See code comments.
DeleteWithCheckboxComponentController.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
({ loadContactList: function(component, event, helper) { // call the helper function for fetch contact from apex class helper.onLoad(component, event); }, // For count the selected checkboxes. checkboxSelect: function(component, event, helper) { // get the selected checkbox value var selectedRec = event.getSource().get("v.value"); // get the selectedCount attrbute value(default is 0) for add/less numbers. var getSelectedNumber = component.get("v.selectedCount"); // check, if selected checkbox value is true then increment getSelectedNumber with 1 // else Decrement the getSelectedNumber with 1 if (selectedRec == true) { getSelectedNumber++; } else { getSelectedNumber--; } // set the actual value on selectedCount attribute to show on header part. component.set("v.selectedCount", getSelectedNumber); }, // For select all Checkboxes selectAll: function(component, event, helper) { //get the header checkbox value var selectedHeaderCheck = event.getSource().get("v.value"); // get all checkbox on table with "boxPack" aura id (all iterate value have same Id) // return the List of all checkboxs element var getAllId = component.find("boxPack"); // If the local ID is unique[in single record case], find() returns the component. not array if(! Array.isArray(getAllId)){ if(selectedHeaderCheck == true){ component.find("boxPack").set("v.value", true); component.set("v.selectedCount", 1); }else{ component.find("boxPack").set("v.value", false); component.set("v.selectedCount", 0); } }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); component.set("v.selectedCount", getAllId.length); } } else { for (var i = 0; i < getAllId.length; i++) { component.find("boxPack")[i].set("v.value", false); component.set("v.selectedCount", 0); } } } }, //For Delete selected records deleteSelected: function(component, event, helper) { // create var for store record id's for selected checkboxes var delId = []; // get all checkboxes var getAllId = component.find("boxPack"); // If the local ID is unique[in single record case], find() returns the component. not array if(! Array.isArray(getAllId)){ if (getAllId.get("v.value") == true) { delId.push(getAllId.get("v.text")); } }else{ // play a for loop and check every checkbox values // if value is checked(true) then add those Id (store in Text attribute on checkbox) in delId var. for (var i = 0; i < getAllId.length; i++) { if (getAllId[i].get("v.value") == true) { delId.push(getAllId[i].get("v.text")); } } } // call the helper function and pass all selected record id's. helper.deleteSelectedHelper(component, event, delId); }, }) |
- See code comments.
DeleteWithCheckboxHelper.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
({ onLoad: function(component, event) { console.log('onLoad call'); //call apex class method var action = component.get('c.fetchContact'); action.setCallback(this, function(response) { //store state of response var state = response.getState(); if (state === "SUCCESS") { //set response value in ListOfContact attribute on component. component.set('v.ListOfContact', response.getReturnValue()); // set deafult count and select all checkbox value to false on load component.set("v.selectedCount", 0); component.find("box3").set("v.value", false); } }); $A.enqueueAction(action); }, deleteSelectedHelper: function(component, event, deleteRecordsIds) { //call apex class method var action = component.get('c.deleteRecords'); // pass the all selected record's Id's to apex method action.setParams({ "lstRecordId": deleteRecordsIds }); action.setCallback(this, function(response) { //store state of response var state = response.getState(); if (state === "SUCCESS") { console.log(state); if (response.getReturnValue() != '') { // if getting any error while delete the records , then display a alert msg/ alert('The following error has occurred. while Delete record-->' + response.getReturnValue()); } else { console.log('check it--> delete successful'); } // call the onLoad function for refresh the List view this.onLoad(component, event); } }); $A.enqueueAction(action); }, }) |
- See code comments.
TestApp.app
1 2 3 4 5 6 7 8 |
<aura:application extends="force:slds"> <c:DeleteWithCheckboxComponent /> <!-- here c: is org. namespace prefix--> </aura:application> |
- After the winter 17 release you can use the Lightning Design System style in Lightning Apps by extends=”fore:slds”. The Salesforce Lightning Design System provides a look & feel that’s consistent with Lightning Experience. Use Lightning Design System styles to give your custom applications a UI that is consistent with Salesforce.
Some Useful Resources :
Lightning design style checkbox
https://www.lightningdesignsystem.com/components/data-tables/
Like our facebook page for new post updates.? & Don’t forget to bookmark this site for your future reference. ?
if you have any suggestions or issue with it, you can post in comment box 🙂
29 comments
Awesome, very helpful. Had to implement the similar feature and this helped a lot
thanks for your feedback @Apoorv Jain 🙂
Hi ,
When I am trying to put this component on a lighting page layout , I am getting this error message :
“Unfortunately, there was a problem. Please try again. If the problem continues, get in touch with your administrator with the error ID shown here and any other related details. This page has an error. You might just need to refresh it. Action failed: c:DeleteWithCheckboxComponent$controller$doneWaiting [Cannot read property ‘style’ of null] Failing descriptor: {c:DeleteWithCheckboxComponent$controller$doneWaiting}”
NOTE : with individual app it’s working fine
can you please help me out on this
thanks
hi Apoorv Jain
can you share your component code
you can post your query on
http://sfdcmonkey.com/community/main-forum/
thanks
Nice posts Piyush soni
thanks for your feedback Raghava bro. 🙂
Hi
I’m getting one issue, if there is only 1 contact;
And we select, SelectAll option, then the 1 contact is not getting selected.
hi john,
can you share your issue on
http://sfdcmonkey.com/community/main-forum/
in details so i can review and fix it because above code is working fine for me with single contact select
thanks
i’m facing same Problem which John is Facing… This code is not working for Single Record..
Hi philips, i have fixed this issue and update the code please check
Hi John,
By default it consider a variable as an object. You need to convert it to an array, if it returns only one record.
var getAllId = [];
getAllId = component.find(“cbselected”);
if (!Array.isArray(getAllId)) {
getAllId = [getAllId];
}
Try something like this. It should work.
Thanks
Brahma
How to Add Multiple rows in a Lighnting Component
If you click (+) a new row with all data will be populated
I have a question. Where is the event registered? As you are using the event to get the value in selectAll method. Can you let me know where the event was registered in component?
if possible can you post the event code too.
Basically this event is Standard Lightning event binding with ‘event’ parameter in method it, means we are getting the value of that particulate Header checkbox which is selected and on the selection this ‘selectALl’ method will be fire, if it will be true then ‘event.getSource().get(“v.value”);’ return true if it false then it will be return false, simple 🙂
Hops it helps
Cool. Thanks for the explanation.
Suppose if the checkbox is selected then only we need to display the Delete Contact button as a separate component but not on the header. If checkbox is not selected then the Delete contact button should not be displayed.
I mean to say instead of a button here can we create a panel component to display the Delete contact button depending on the checkbox selected or not instead of displaying it on the header everytime.
Can you let me know how to do this and how to communicate between the components when doing this? Appreciate if you can post a code for this.
Hi..This doesn’t work with one record. component.find() is not working if their is only one record in the table. Try limiting the record to 1 and see if it works.
Hi Ali, i have fixed this issue and update the code please check
Hi Piyush,
I need to check some records accordingly and i have to download only the checked records not all records. Is it possible you can share me some relevant code.
Many thanks.
Hi Piyush,
I need to query records from oportunity with checkbox next to each records. The functionality is, suppose I select 3 checkboxes i.e 3 records, I need to download detail pages of those 3 selected records by keeping a custom button. I need to achieve this functionality in lightning. Can you pls help with code.
Awesome.. 🙂
Hi Piyush,
Will we make this Dynamic like ,if i wanna do this on account,opportunity …
thanks.
I am doing something very similar but I am using my table to close Tasks. Unfortunately, I cannot get the “v.text” value (each individual Task ID) to come over to the controller and I am not sure what I am doing wrong.
Great article
@sfdcmonkey
I need to workout a lot of tasks in lightning,where i can get list of tasks to be worked out.
If you have any links or list of tasks kindly share with me.
Hi,
Thank you so much for this example everything is good until I change ui buttons to lightning buttons, could you please suggest how can we use lightning buttons with this?
@sfdcmonkey
Could you make same functionality with Lightning:Datatable ?
Thanks!!
How to insert serial number column here?
Thanks for the nice post. I try to update records from list view. Can you suggest me how to get number of records successfully updated and failed to update records in list view.
Thanks in advance !!!
Sathik