delete-multiple-records-using-checkbox-lightning-WebComponent
==========
public class AccountDeleteController{
@AuraEnabled(cacheable=true)
public static List<Account> displayAccounts(){
return [select Id,Name from Account ];
}
@AuraEnabled
public static List<Account> delAccRecords(String jsonCode){
System.debug('JSONCODE'+jsonCode);
List<Account> accIds = (List<Account>) JSON.deserialize(jsonCode, List<Account>.class);
List<Account> delacclist=new List<Account>();
for(Account acc:[select Id,Name from Account where Id in:accIds]){
delacclist.add(acc);
}
if(delacclist.size()>0){
try{
delete delacclist;
}
catch(Exception e){
throw new AuraHandledException(e.getMessage());
}
}
return displayAccounts();
}
}
deleteRecords.html
==================
<template>
<lightning-button label="Delete" variant="brand" onclick={handleDelete}>
</lightning-button>
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
<tr>
<td>
<lightning-input onchange={handleSelectAll} type="checkbox"></lightning-input>
</td>
<td>
<b>Name</b>
</td>
</tr>
<template for:each={accounts.data} for:item="acc">
<tr key={acc.Id}>
<td>
<lightning-input type="checkbox" value={acc.Id} data-id={acc.Id}></lightning-input>
</td>
<td>
{acc.Name}
</td>
</tr>
</template>
</table>
</template>
deleteRecords.js
================
import { LightningElement, track, wire } from 'lwc';
import displayAccounts from '@salesforce/apex/AccountDeleteController.displayAccounts';
import delAccRecords from '@salesforce/apex/AccountDeleteController.delAccRecords';
import {refreshApex} from '@salesforce/apex';
export default class DeleteRecords extends LightningElement {
@track error;
@track selectedAccRecords=[];
@track errorMessage;
@track JSONString;
@wire(displayAccounts) accounts;
handleSelectAll(event) {
let selectedRows = this.template.querySelectorAll('lightning-input');
for(let i = 0; i < selectedRows.length; i++) {
if(selectedRows[i].type === 'checkbox') {
selectedRows[i].checked = event.target.checked;
}
}
}
handleDelete() {
let selectedRows = this.template.querySelectorAll('lightning-input');
for(let i = 0; i < selectedRows.length; i++) {
if(selectedRows[i].checked && selectedRows[i].type === 'checkbox') {
this.selectedAccRecords.push({
Id: selectedRows[i].dataset.id
})
}
this.JSONString=JSON.stringify(this.selectedAccRecords);
console.log('@@@@AccountIds@@@'+this.JSONString);
}
delAccRecords({jsonCode:this.JSONString})
.then(()=>{
this.template.querySelectorAll('lightning-input').selectedRows=[];
return refreshApex(this.accounts)
})
.catch((error)=>{
this.errorMessage=error;
console.log('unable to delete the record due to'+JSON.stringify(this.errorMessage));
});
}
}
LightningApplication
====================
<aura:application extends="force:slds">
<c:deleteRecords>
</c:deleteRecords>
</aura:application>
Comments
Post a Comment