LWC to create a custom editable datatable.

|
| By Webner

LWC also provides a standard editable datatable, but it can’t be flexible in design. So we can create a custom datatable by using LWC in the following way, in which we can make changes as per our needs.

LWC HTML Code for datatable:

Datatable

LWC JS Code for datatable:

import { LightningElement, track } from 'lwc';
import saveAccountsLwc from '@salesforce/apex/editTableController.saveAccountsLwc';
import getAccounts from '@salesforce/apex/editTableController.getAccounts';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class LwcListEditable extends LightningElement {
@track isEdited = false;
@track toggleSaveLabel = 'Save';
@track myList = [];
editAccount() {
this.isEdited = true;
}
accountDataChange(event) {
let fieldName = event.target.dataset.fieldName;
let element = this.myList.find(ele => ele.Id === event.target.dataset.id);
element[fieldName] = event.target.value;
this.myList = [...this.myList];
console.log(JSON.stringify(this.myList));
}
handleSave() {
this.toggleSaveLabel = 'Saving...'
let toSaveList = this.myList;
toSaveList.forEach((element, index) => {
if(element.Name === ''){
toSaveList.splice(index, 1);
}
});
this.myList = toSaveList;
saveAccountsLwc({records : toSaveList})
.then(() => {
this.toggleSaveLabel = 'Saved';
this.dispatchEvent(
new ShowToastEvent({
title : 'Success',
message : `Records saved succesfully!`,
variant : 'success',
}),
)
this.getAccountRecords();
this.isEdited = false;
this.error = undefined;
})
.catch(error => {
this.error = error;
this.record = undefined;
console.log("Error in Save call back:", this.error);
})
.finally(() => {
setTimeout(() => {
this.toggleSaveLabel = 'Save';
}, 3000);
});
}
connectedCallback() {
this.getAccountRecords();
}
getAccountRecords() {
getAccounts()
.then(result => {
this.record = result;
this.myList = this.record;
this.error = undefined;
})
.catch(error => {
this.error = error;
this.record = undefined;
});
}
handleCancel() {
this.isEdited = false;
}
}

Apex Class Code:

public with sharing class editTableController {
@AuraEnabled
public static void saveAccountsLwc(List<account> records){
if(records.size()>0 && records != null){
List<account> accs = new List<account>();
for(integer i = 0; i < records.size(); i++) {
account acc = new account();
acc.Id = records[i].Id;
acc.Name = records[i].Name;
acc.Email = records[i].Email;
accs.add(acc);
}
upsert accs;
}
}
@AuraEnabled
public static List<Account> getAccounts(){
return [SELECT Id, Name, Email From ACCOUNT LIMIT 10];
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *