Delete Multiple Records Using Checkbox In Lightning Component using DataTable
Lightning Component:
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordId,flexipage:availableForRecordHome,force:lightningQuickAction" access="global" controller="LightningDataTableContactClass">
<aura:attribute name="data" type="Object"/>
<aura:attribute name="columns" type="List"/>
<aura:attribute name="recordId" type="String"/>
<aura:attribute name="updatedRecord" type="Object[]" />
<aura:attribute name="selectedCons" type="List"/>
<aura:attribute name="totalRecordsCount" type="Integer"/>
<aura:attribute name="selectedCount" type="integer" default="0"
description="selected Records Count"/>
<aura:attribute name="Message" type="boolean" default="false" description="use for display no record found message"/>
<aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
<!-- SHOW LOADING SPINNER-->
<lightning:spinner variant="brand" size="large" aura:id="Id_spinner" class="slds-hide" />
<lightning:card title="Contact Datatable">
<aura:if isTrue="{!v.Message}">
<div class="slds-notify_container slds-is-relative">
<div class="slds-notify slds-notify_toast slds-theme_error" role="alert">
<div class="slds-notify__content">
<h2 class="slds-text-heading_small">No Records Found...</h2>
</div>
</div>
</div>
</aura:if>
<div class="slds-grid slds-grid--align-Start">
<!-- Selected Contact:{!v.selectedCount}-->
<b> Total Records : {!v.selectedCount > 0 ? v.selectedCount + '/' : ''} {!v.totalRecordsCount}</b>
</div>
<div class="slds-grid slds-grid--align-end">
<button class="slds-button slds-button--brand" onclick="{!c.deleteSelected}">Delete Contact</button>
</div>
<lightning:datatable
aura:id="ContactDataTable"
columns="{! v.columns }"
data="{! v.data }"
keyField="Id"
onsave ="{!c.onSave}"
hideCheckboxColumn="false"
onrowselection="{!c.handleSelect}"/>
</lightning:card>
</aura:component>
Client Controller :
({
doInit : function(component, event, helper) {
component.set('v.columns', [
// {label: 'Name', fieldName: 'Name', editable:'true', type: 'text'},
{label: 'Name', fieldName: 'LinkName', type: 'url',typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'}},
{label: 'FirstName', fieldName: 'FirstName', editable:'true', type: 'text'},
{label: 'LastName', fieldName: 'LastName', editable:'true', type: 'text'},
{label: 'Phone', fieldName: 'MobilePhone', editable:'true', type: 'phone'},
{label: 'Email', fieldName: 'Email', editable:'true', type: 'Email'},
{label: 'Department', fieldName: 'Department', editable:'true', type: 'text'}
]);
helper.fetchContacts(component, helper);
},
onSave : function (component, event, helper) {
helper.saveDataTable(component, event, helper);
},
handleSelect : function( component, event, helper ) {
var selectedRows = event.getParam( 'selectedRows' );
component.set( "v.selectedCount", selectedRows.length);
var setRows = [];
for ( var i = 0; i < selectedRows.length; i++ ) {
setRows.push( selectedRows[i] );
}
component.set( "v.selectedCons", setRows );
},
deleteSelected: function(component, event, helper) {
// alert('Hello');
var delId = [];
var getAllId = component.get( "v.selectedCons" );
// var getAllId = component.find("ContactDataTable");
if(! Array.isArray(getAllId)){
alert('Test fail');
if (getAllId.get("v.value") == true) {
delId.push(getAllId.get("v.text"));
}
}else{
for (var i = 0; i < getAllId.length; i++) {
if (getAllId[i].Id != '') {
delId.push(getAllId[i].Id);
// alert('Hello: '+delId);
}
}
}
helper.deleteSelectedHelper(component, event, delId);
},
})
Client Helper :
({
fetchContacts : function(component, event, helper) {
var action = component.get("c.fetchContacts");
var recordId = component.get("v.recordId");
action.setParams({
'recordId' : recordId
});
action.setCallback(this,function(response) {
var state = response.getState();
if (state === "SUCCESS") {
var records =response.getReturnValue();
if(records.length > 0){
records.forEach(function(record){
record.LinkName = '/'+record.Id;
});
component.set("v.data", records);
component.set("v.totalRecordsCount", records.length);
}else{
// if there is no records then display message
component.set("v.Message" , true);
}
}
else{
alert('Error...');
}
});
$A.enqueueAction(action);
},
saveDataTable : function(component, event, helper) {
var editedRecords = component.find("ContactDataTable").get("v.draftValues");
var totalRecordEdited = editedRecords.length;
var action = component.get("c.updateContacts");
action.setParams({
'editedContactList' : editedRecords
});
action.setCallback(this,function(response) {
var state = response.getState();
if (state === "SUCCESS") {
//if update is successful
if(response.getReturnValue() === true){
helper.showToast({
"title": "Record Update",
"type": "success",
"message": totalRecordEdited+" Contact Records Updated"
});
// helper.reloadDataTable();
window.location.reload(false);
} else{ //if update got failed
helper.showToast({
"title": "Error!!",
"type": "error",
"message": "Error in update"
});
}
}
});
$A.enqueueAction(action);
},
deleteSelectedHelper: function(component, event, deleteRecordsIds) {
component.find("Id_spinner").set("v.class" , 'slds-show');
var action = component.get('c.deleteRecords');
action.setParams({
"lstRecordId": deleteRecordsIds
});
action.setCallback(this, function(response) {
component.find("Id_spinner").set("v.class" , 'slds-hide');
var state = response.getState();
if (state === "SUCCESS") {
if (response.getReturnValue() != '') {
// alert('The following error has occurred. while Delete record-->' + response.getReturnValue());
var errors = response.getReturnValue();
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
"type":"error",
"title": "Error!",
"message": "Error in Delete!"
});
toastEvent.fire();
} else {
//alert('successful delete contact');
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
"type":"Success",
"title": "successful delete contact",
"message": "successful delete contact"
});
toastEvent.fire();
}
// this.fetchContacts(component, event);
}
});
$A.enqueueAction(action);
},
showToast : function(params){
var toastEvent = $A.get("e.force:showToast");
if(toastEvent){
toastEvent.setParams(params);
toastEvent.fire();
} else{
alert(params.message);
}
},
reloadDataTable : function(){
var refreshEvent = $A.get("e.force:refreshView");
if(refreshEvent){
refreshEvent.fire();
}
},
})
Server Controller:
public class LightningDataTableContactClass {
@AuraEnabled
public static list <contact> fetchContacts(Id recordId) {
system.debug('record Id : '+recordId);
list <contact> returnConList = new List <contact> ();
List <contact> lstCon = [SELECT Name, firstName, LastName, Department, MobilePhone,Email From contact where accountid =: recordId LIMIT 50];
for (contact c: lstCon) {
returnConList.add(c);
}
// return the List of contacts
return returnConList;
}
@AuraEnabled
public static boolean updateContacts(List<Contact> editedContactList){
try{
update editedContactList;
return true;
} catch(Exception e){
return false;
}
}
@AuraEnabled
public static List<String> deleteRecords(List<String> lstRecordId) {
system.debug('---------> : '+lstRecordId);
List <String> oErrorMsg = new List <String> ();
List <contact> lstDeleteRec = [select Id from contact where id IN: lstRecordId];
Database.DeleteResult[] DR_Dels = Database.delete(lstDeleteRec, false);
for (Database.DeleteResult dr: DR_Dels) {
if (dr.isSuccess()) {
system.debug('successful delete contact');
oErrorMsg.add('');
} else {
oErrorMsg.add('');
for (Database.Error err: dr.getErrors()) {
oErrorMsg.add(err.getStatusCode() + ': ' + err.getMessage());
}
}
}
return oErrorMsg;
}
@AuraEnabled
public static List<Contact> SearchContact(String searchKeyWord) {
String searchKey = '%'+searchKeyWord + '%';
List<Contact> returnList = new List<Contact> ();
List<Contact> lstOfContact = [SELECT Name, FirstName, LastName, Department, MobilePhone,Email From contact
where Name LIKE: searchKey LIMIT 500];
for (Contact Con: lstOfContact) {
returnList.add(Con);
}
return returnList;
}
}
No comments:
Post a Comment