Mass Delete Records in LWC Datatable

by Mohmmad Juber
0 comment

Hello friends, today we are going to discuss Mass Delete Records in LWC Datatable. Delete Multiple Records in a DataTable is a crucial aspect of any web application, and providing users with the ability to delete multiple records in a DataTable can significantly enhance the user experience. In this blog, we’ll explore the process of implementing a feature that allows users to seamlessly delete multiple records from an LWC DataTable – a common requirement in many dynamic web applications.

Also, check this: Delete Records in Flow Salesforce

Key Highlights :

  1. User Empowerment: Give users the ability to manage data efficiently without relying on manual deletion processes.
  2. Efficiency Amplified: Quickly purge unwanted records, maintaining a lean and responsive Salesforce environment.
  3. Customizable Experience: Tailor the mass delete functionality to align with your organization’s specific requirements.

Code :

MassDeleteRecordInDatatableHandler.cls

public class MassDeleteRecordInDatatableHandler {
    @AuraEnabled(cacheable = true)
    public static List<Account> fetchAccount() {
        return [ SELECT Id, Name, Fax, Phone FROM Account limit 10];    
    }
    
    @AuraEnabled
    public static void deleteSelectedAccounts(List<Account> accountList) {
        delete accountList;
    }
}

massDeleteRecordInDatatableLWC.html :

<template>
	<lightning-card title="Mass Delete Records in LWC Datatable" icon-name="utility:recycle_bin_full">
		<div style="width: auto;">
			<template if:true={data}>
				<lightning-layout>
					<lightning-layout-Item padding="around-small" size="10">
						<span><p>&nbsp;<b><i>Selected Records: {recordsCount}</i></b></p></span>
					</lightning-layout-Item>
                                        <lightning-layout-Item padding="around-small" size="2">
						<lightning-button label={buttonLabel} icon-name="utility:delete" disabled={isTrue}
							variant="destructive" onclick={deleteRecords}>
						</lightning-button>
					</lightning-layout-Item>
				</lightning-layout>
				<lightning-datatable data={data} columns={columns} key-field="id" onrowselection={getSelectedRecords}>
				</lightning-datatable>
			</template>
		</div>
	</lightning-card>
 </template>

massDeleteRecordInDatatableLWC.js :

import { LightningElement, track, wire } from 'lwc';
import fetchAccount from '@salesforce/apex/MassDeleteRecordInDatatableHandler.fetchAccount';
import deleteSelectedAccounts from '@salesforce/apex/MassDeleteRecordInDatatableHandler.deleteSelectedAccounts';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { refreshApex } from '@salesforce/apex';
const columns = [
    {
        label: 'Name',
        fieldName: 'Name'
    }, {
        label: 'Fax',
        fieldName: 'Fax'
    }, {
        label: 'Phone',
        fieldName: 'Phone',
        type: 'phone'
    }
];
export default class MassDeleteRecordInDatatableLWC extends LightningElement {
    @track data;
    @track columns = columns;
    @track buttonLabel = 'Delete Records';
    @track isDisableTrue = false;
    @track recordsCount = 0;
    selectedRecords = [];
    refreshTable;
    error;

    @wire(fetchAccount)
    Accounts(result) {
        this.refreshTable = result;
        if (result.data) {
            this.data = result.data;
            this.error = undefined;
        } else if (result.error) {
            this.error = result.error;
            this.data = undefined;
        }
    }

    getSelectedRecords(event) {
        const selectedRows = event.detail.selectedRows;
        this.recordsCount = event.detail.selectedRows.length;
        this.selectedRecords = new Array();
        selectedRows.forEach(ele=>{
            this.selectedRecords.push(ele);
        });
    }

    deleteRecords() {
        if (this.selectedRecords) {
            this.buttonLabel = 'Processing..';
            this.isDisableTrue = true;
            
            deleteSelectedAccounts({ accountList: this.selectedRecords }).then(result => {
                console.log('result =>', result);
                this.buttonLabel = 'Delete Records';
                this.isDisableTrue = false;
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success!!',
                        message: this.recordsCount + ' Account records deleted.',
                        variant: 'success'
                    }),
                );
                this.template.querySelector('lightning-datatable').selectedRows = [];
                this.recordsCount = 0;
                return refreshApex(this.refreshTable);
            }).catch(error => {
                this.buttonLabel = 'Delete Records';
                this.isDisableTrue = false;
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error while delete Accounts',
                        message: JSON.stringify(error),
                        variant: 'error'
                    }),
                );
            });
        }
    }
}

contactLIghtingDataTable.js-meta.xml

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
	<apiVersion>57.0</apiVersion>
	<isExposed>true</isExposed>
	<targets>
		<target>lightning__HomePage</target>
		<target>lightning__Tab</target>
	</targets>
</LightningComponentBundle>

Output :

Mass Delete Records in LWC Datatable

Reference :

  1. LWC Datatable
What’s your Reaction?
+1
2
+1
0
+1
0
+1
0
+1
2
+1
0

You may also like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.