Apex Class
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(String accId) {
return [
SELECT AccountId, Id, FirstName, LastName, Title, Phone, Email
FROM Contact
WHERE AccountId = :accId
WITH SECURITY_ENFORCED
];
}
}
HTML
<template>
<lightning-card title="Datatable Example" icon-name="custom:custom63">
<div class="slds-m-around_medium">
<template lwc:if={contacts.data}>
<lightning-datatable
key-field="Id"
data={contacts.data}
columns={columns}
onsave={handleSave}
draft-values={draftValues}>
</lightning-datatable>
</template>
<template lwc:if={contacts.error}>
<!-- handle Apex error -->
</template>
</div>
</lightning-card>
</template>
Java Script
import { LightningElement, wire, api } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContactList';
import { refreshApex } from '@salesforce/apex';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import FIRSTNAME_FIELD from '@salesforce/schema/Contact.FirstName';
import LASTNAME_FIELD from '@salesforce/schema/Contact.LastName';
import TITLE_FIELD from '@salesforce/schema/Contact.Title';
import PHONE_FIELD from '@salesforce/schema/Contact.Phone';
import EMAIL_FIELD from '@salesforce/schema/Contact.Email';
import ID_FIELD from '@salesforce/schema/Contact.Id';
const COLS = [
{
label: 'First Name',
fieldName: FIRSTNAME_FIELD.fieldApiName,
editable: true
},
{
label: 'Last Name',
fieldName: LASTNAME_FIELD.fieldApiName,
editable: true
},
{ label: 'Title', fieldName: TITLE_FIELD.fieldApiName, editable: true },
{
label: 'Phone',
fieldName: PHONE_FIELD.fieldApiName,
type: 'phone',
editable: true
},
{
label: 'Email',
fieldName: EMAIL_FIELD.fieldApiName,
type: 'email',
editable: true
}
];
export default class DatatableInlineEditWithUiApi extends LightningElement {
@api recordId;
columns = COLS;
draftValues = [];
@wire(getContacts, { accId: '$recordId' })
contacts;
async handleSave(event) {
// Convert datatable draft values into record objects
const records = event.detail.draftValues.slice().map((draftValue) => {
const fields = Object.assign({}, draftValue);
return { fields };
});
// Clear all datatable draft values
this.draftValues = [];
try {
// Update all records in parallel thanks to the UI API
const recordUpdatePromises = records.map((record) =>
updateRecord(record)
);
await Promise.all(recordUpdatePromises);
// Report success with a toast
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'Contacts updated',
variant: 'success'
})
);
// Display fresh data in the datatable
await refreshApex(this.contacts);
} catch (error) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Error updating or reloading contacts',
message: error.body.message,
variant: 'error'
})
);
}
}
}
Video
Video does not exists.