This post explains, inline editing in lightning-datatable in salesforce lightning web components(lwc).
HTML Code:
<template>
<lightning-card title="Inline Edit With Lightning Datatable in LWC">
<template if:true={contacts.data}>
<lightning-datatable key-field="Id"
data={contacts.data}
columns={columns}
onsave={handleSave}
draft-values={saveDraftValues}
hide-checkbox-column
show-row-number-column>
</lightning-datatable>
</template>
</lightning-card>
</template>
Javascript Code:
import { LightningElement, wire, track } from 'lwc';
import getContacts from '@salesforce/apex/LWCExampleController.getContacts';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { refreshApex } from '@salesforce/apex';
const columns = [
{
label: 'Name',
fieldName: 'Name',
type: 'text',
}, {
label: 'FirstName',
fieldName: 'FirstName',
type: 'text',
editable: true,
}, {
label: 'LastName',
fieldName: 'LastName',
type: 'text',
editable: true,
}, {
label: 'Phone',
fieldName: 'Phone',
type: 'phone',
editable: true
}
];
export default class InlineEditTable extends LightningElement {
columns = columns;
@track contacts;
saveDraftValues = [];
@wire(getContacts)
cons(result) {
this.contacts = result;
if (result.error) {
this.contacts = undefined;
}
};
handleSave(event) {
this.saveDraftValues = event.detail.draftValues;
const recordInputs = this.saveDraftValues.slice().map(draft => {
const fields = Object.assign({}, draft);
return { fields };
});
const promises = recordInputs.map(recordInput => updateRecord(recordInput));
Promise.all(promises).then(res => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'Records Updated Successfully!!',
variant: 'success'
})
);
this.saveDraftValues = [];
return this.refresh();
}).catch(error => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Error',
message: 'An Error Occured!!',
variant: 'error'
})
);
}).finally(() => {
this.saveDraftValues = [];
});
}
async refresh() {
await refreshApex(this.contacts);
}
}
Apex Code:
public inherited sharing class LWCExampleController {
@AuraEnabled(Cacheable = true)
public static List<Contact> getContacts() {
return [SELECT Id, Name, FirstName, LastName, Phone, Email
FROM Contact
WHERE Email != null
AND Phone != null
ORDER BY CreatedDate DESC NULLS LAST limit 10];
}
}
Output: