Hello Everyone, in this post let’s check out how we can delete records dynamically by using the checkbox in the lightning component.
Table of Contents
Delete Row Dynamically In Salesforce Lightning.
For the table display, we have used a standard lighting data table to display the table and fetched the record Ids of particular rows selected and stored them in an attribute and on that showed a count of selected records, and before deleting the selected rows shown the modal that asks for confirmation. Let’s check out the implementation part of this component.
Step 1 :- Create Server Side Apex Controller
public class LeadHandler {
@AuraEnabled
public static List<Lead> featchLead() {
//Returning list of leads.
return [SELECT Id, Name,Company,Status,Phone,Email FROM Lead];
}
@AuraEnabled
public static void DeleteRecord(List<Lead> DeleteIds) {
List<Lead> delacccon = new List<Lead>();
for(Lead con : [SELECT Id, Name,Company,Status,Phone,Email FROM Lead WHERE Id IN : DeleteIds]){
delacccon.add(con);
}
if(delacccon.size() > 0){
Delete delacccon;
}
}
}
Step 2: – DisplayLeadAndDelete.Cmp
<aura:component implements="flexipage:availableForAllPageTypes" access="global" controller="LeadHandler">
<!--Used to load the data-->
<aura:handler name="init" value="{! this }" action="{! c.init }"/>
<!--Force:refreshView is an event that can be used to refresh the view.-->
<aura:handler event="force:refreshView" action="{!c.init}" />
<aura:attribute name="columns" type="List"/>
<aura:attribute name="data" type="Object"/>
<aura:attribute name="selectedLeads" type="List"/>
<aura:attribute name="selectedRowsCount" type="Integer" default="0"/>
<aura:attribute name="showDeleteBox" type="boolean" default="false"/>
<aura:attribute name="ButtonShow" type="boolean" default="false"/>
<lightning:card title="Lead Details">
<div class="slds-clearfix">
<div class="slds-m-left_medium"> Selected Leads: {! v.selectedRowsCount }</div>
<div class="slds-float_right">
<aura:if isTrue="{!v.ButtonShow}">
<lightning:button variant="brand" label="Delete Lead" title="Brand action" onclick="{!c.handleConfirmDialog }" class="slds-m-bottom_large"/>
</aura:if>
</div>
</div>
<div style="height: 300px">
<lightning:datatable
columns="{! v.columns }"
data="{! v.data }"
keyField="id"
onrowselection="{! c.updateSelectedText}"
/>
</div>
</lightning:card>
<!--Added if to render the modal for confirmation.-->
<aura:if isTrue="{!v.showDeleteBox}">
<div role="dialog" class="slds-modal slds-fade-in-open ">
<div class="slds-modal__container">
<header class="slds-modal__header">
<h1 class="slds-text-heading--medium">Confirmation to Delete Selected Records.</h1>
</header>
<div class="slds-modal__content slds-p-around--medium">
<center><b>If you click Delete records will be deleted or Cancel to stay on this page.</b></center>
</div>
<footer class="slds-modal__footer">
<lightning:button name='Cancel' label='Cancel' onclick='{!c.handleConfirmDialogCancel}'/>
<lightning:button variant="brand" name='Delete' label='Delete' onclick='{!c.handleClick}'/>
</footer>
</div>
</div>
<div class="slds-backdrop slds-backdrop--open"></div>
</aura:if>
</aura:component>
DisplayLeadAndDelete.Js
({
//function to show the leads records.
init : function(component, event, helper) {
//Data-table columns.
component.set('v.columns', [
{label: 'Lead name', fieldName: 'Name', type: 'text'},
{label: 'Company', fieldName: 'Company', type: 'text'},
{label: 'Phone', fieldName: 'Phone', type: 'Phone'},
{label: 'Email', fieldName: 'Email', type: 'Email'},
{label: 'Status', fieldName: 'Status', type: 'Picklist'}
]);
//Calling apex method to featch the lead details.
var action = component.get('c.featchLead');
action.setCallback(this, function(response) {
//store state of response
var state = response.getState();
if (state === "SUCCESS") {
//Storing the reponse from server side to an attribute.
component.set('v.data', response.getReturnValue());
}
});
$A.enqueueAction(action);
},
//Function to fetch recordIds of each row and to show the count.
updateSelectedText: function (component, event) {
//Get sleceted Checkbox rows.
var selectedRows = event.getParam('selectedRows');
//Store a count in an attribute.
component.set('v.selectedRowsCount', selectedRows.length);
//Stored in var to display count in console.
//You can skip next two lines.
var slectCount =selectedRows.length;
console.log('slectCount'+slectCount);
//Created var to store record id's for selected checkboxes.
var setRows = [];
for ( var i = 0; i < selectedRows.length; i++ ) {
setRows.push(selectedRows[i]);
}
//Adding slelected recordIds to an attribute.
component.set("v.selectedLeads", setRows);
console.log('selected data:'+setRows);
//Added this condition to show the button "Delete Leads".
//If checkbox is selected then only it will show else no.
if(slectCount>0){
component.set('v.ButtonShow', true);
}else{
component.set('v.ButtonShow', false);
}
},
//This fucntion to handle a delete functionality.
handleClick : function(component, event, helper){
//Created var that store the recordIds of selected rows.
var records = component.get("v.selectedLeads");
//Console log.
console.log(records);
//Calling helper to perform delete action.
helper.deltingCheckboxAccounts(component, event, records);
},
// function to handle the Modal Popup window.
handleConfirmDialog : function(component, event, helper) {
component.set('v.showDeleteBox', true);
},
//Function to handle Cancel Popup.
handleConfirmDialogCancel : function(component, event, helper) {
console.log('Cancel');
component.set('v.showDeleteBox', false);
},
})
DisplayLeadAndDelete.helper
({
//To perform delete action.
deltingCheckboxAccounts : function(component, event, deltIds) {
//Calling apex method.
var action = component.get('c.DeleteRecord');
//passing the all selected record's Id's to apex method.
action.setParams({
"DeleteIds": deltIds
});
//Getting response.
action.setCallback(this, function(response) {
var state = response.getState();
//If state is sucess then refreshing the View.
if (state === "SUCCESS") {
console.log('Inside delete'+state);
//Refresh the View.
$A.get('e.force:refreshView').fire();
}
});
$A.enqueueAction(action);
}
})
Step 3: – Add to App Page.
You can add to the app page, Home Page, or Record page.
Conclusion
In this post, we learned how we can delete records dynamically using the checkbox. Please share with your colleagues, friends. Feel free to put your thoughts in the comment section below.
Awesome material… Expecting more components like this..
Sure. We will do that in the Coming Days.
Good work Mithun keep it up 🙂
Thanks, Puja.
Great Work!!
Thanks, Megha.
hi
If click delete lead button model box is open after that
Click delete button the records is deleted but the model box is not closing
anybody help me
Hi Aravind,
Could you please check like are you using boolean to set the value and based on that you are showing modal pop up?.