Sub topic 11
Editing cells inline and saving drafts
This chapter adds inline editing to the contact table from the earlier chapters. You will mark columns as editable, handle the save event, write the changes with updateRecord, and clear the table's draft state afterward.
It assumes you have a working lightning-datatable with a key-field, a wired Apex method that stores its result in wiredResult, and basic familiarity with async/await and Promise.all.
How inline editing works
The datatable does not save anything. It tracks what the user typed and tells your component about it. Saving is your job.
When a column is editable, the user can click a cell and type a new value. The table keeps the changed values as draft values and shows a Save and Cancel bar at the bottom. When the user clicks Save, the table fires a save event that carries the drafts. Your handler writes them to Salesforce.
Making columns editable
Add editable: true to each column definition that users may change. Columns without the flag stay read-only.
const COLUMNS = [
{ label: 'Name', fieldName: 'Name', type: 'text', sortable: true },
{ label: 'Email', fieldName: 'Email', type: 'email', editable: true },
{ label: 'Phone', fieldName: 'Phone', type: 'phone', editable: true },
{ label: 'Birthdate', fieldName: 'Birthdate', type: 'date-local', editable: true }
];Name is left read-only on purpose. On Contact, Name is a compound field that Salesforce builds from FirstName and LastName, and you cannot update it directly. To make names editable, query FirstName and LastName separately and give each its own column.
Editable columns work with the common scalar types, such as text, email, phone, url, number, currency, percent, date, date-local, and boolean. Column types that depend on custom markup, such as action or button, are not editable. The table also edits only the value in fieldName. If a column displays a value computed from other fields, editing it does not write back to a record field.
Understanding draft values
Each draft is a plain object with the changed fields and the key-field value. If a user edits the email and phone of one contact, the event detail looks like this:
[
{ Id: '003xx000004TmiQAAS', Email: '[email protected]', Phone: '555-0100' }
]The array has one entry per edited row, and each entry contains only the fields the user changed. This is why the key-field must be the record Id when you save to Salesforce. The draft's Id property is what tells updateRecord which record to update.
Field values arrive as the strings the user typed or as the type the column produces. A date-local column gives YYYY-MM-DD, which is the format Salesforce expects for a Date field.
Binding draft-values
The draft-values attribute connects the table's draft state to a property on your component. Binding it gives you control over when the Save and Cancel bar goes away.
<template>
<lightning-card title="Contacts" icon-name="standard:contact">
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
draft-values={draftValues}
onsave={handleSave}
hide-checkbox-column>
</lightning-datatable>
</lightning-card>
</template>The table fills in the edited cells from its own state. Setting draftValues to an empty array removes every draft and hides the bar. If the user clicks Cancel, the table discards the drafts itself and no save event fires.
Saving with updateRecord
updateRecord from lightning/uiRecordApi takes an object with a fields property. The fields must include Id. The draft already has that, so you can spread it in.
Here is the complete component, combining the earlier pieces with a save handler:
import { LightningElement, wire } from 'lwc';
import { updateRecord } from 'lightning/uiRecordApi';
import { refreshApex } from '@salesforce/apex';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import getContacts from '@salesforce/apex/ContactController.getContacts';
const COLUMNS = [
{ label: 'Name', fieldName: 'Name', type: 'text' },
{ label: 'Email', fieldName: 'Email', type: 'email', editable: true },
{ label: 'Phone', fieldName: 'Phone', type: 'phone', editable: true },
{ label: 'Birthdate', fieldName: 'Birthdate', type: 'date-local', editable: true }
];
export default class ContactTable extends LightningElement {
columns = COLUMNS;
data = [];
error;
wiredResult;
draftValues = [];
@wire(getContacts)
wiredContacts(result) {
this.wiredResult = result;
const { data, error } = result;
if (data) {
this.data = data;
this.error = undefined;
} else if (error) {
this.error = error;
this.data = [];
}
}
async handleSave(event) {
const updates = event.detail.draftValues.map((draft) => ({
fields: { ...draft }
}));
try {
await Promise.all(updates.map((record) => updateRecord(record)));
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'Contacts updated',
variant: 'success'
})
);
this.draftValues = [];
await refreshApex(this.wiredResult);
} catch (e) {
this.error = e;
this.dispatchEvent(
new ShowToastEvent({
title: 'Error updating contacts',
message: e.body?.message ?? 'Unknown error',
variant: 'error'
})
);
}
}
}Three details in the handler matter.
- The drafts are saved in parallel with
Promise.all. This is fast, but the order is not guaranteed and the records are independent updates, not one transaction. this.draftValues = []runs only after every update succeeds. If anything fails, the drafts stay in the table so the user can fix the value and click Save again.refreshApexruns after the clear, so the table shows the saved values from the server.
Why refreshApex is needed
updateRecord writes through Lightning Data Service, which updates its own cache and any lightning/uiRecordApi wire adapters watching those records. Your data comes from a cacheable Apex method, and Lightning Data Service does not track that result. Without refreshApex, the table would keep showing the old values even though Salesforce has the new ones. Passing the whole wiredResult object, not just data, is what lets refreshApex know which wire to re-run.
Partial failures
Promise.all rejects as soon as one update fails, but the other updates keep running. After a failure, some records may already be saved while the table still shows every draft. The catch block above reports the error but does not know which rows succeeded.
You can handle this in a few ways:
| Approach | What it does | Trade-off |
|---|---|---|
| `Promise.all` (shown above) | Fast, fails on the first rejection | Cannot tell which rows saved |
| `Promise.allSettled` | Waits for every update, returns each outcome | You must filter results and keep only failed drafts |
| One Apex method taking all drafts | Saves in a single call, can use `Database.update` with `allOrNone` | Needs custom Apex and your own validation |
With Promise.allSettled, keep only the drafts whose update was rejected and assign that list back to draftValues. The user then sees just the rows that still need attention. Showing per-row messages inside the table is covered in the error display chapter.
Common mistakes
- The Save bar never disappears. You bound
draft-valuesor relied on the table, but you did not setdraftValues = []after the save. The table only clears drafts itself on Cancel. updateRecordfails with a missing Id. Thekey-fieldis not the record Id. The draft then has noIdproperty. Setkey-field="Id".- The table shows old values after saving. You skipped
refreshApex, or you passeddatainstead of the wire result object. - Saving a compound field.
Name,Addressand similar compound fields are not updatable. Use their component fields. - Editing sorted data. The sort handler from the earlier chapter reorders a copy of
data. AfterrefreshApexthe wire emits fresh data in the Apex order, so reapply the current sort if you want to keep it.
Reading drafts without saving
The table also fires cellchange whenever a user edits a cell, before any save. Its event.detail.draftValues holds the drafts that changed in that event. Use it for live validation or to enable and disable other buttons on the page. You do not need it for a basic save.
Exercise
A user edits the Email cell of two contacts and clicks Save. Your handler calls updateRecord for each draft, both succeed, but the Save and Cancel bar stays visible and the table still shows the old emails. What two lines are missing, and in what order should they run?
Show answer
Missing are this.draftValues = []; and await refreshApex(this.wiredResult);. Clear the drafts first, then refresh. The first line removes the Save and Cancel bar, since the table clears drafts only when the user cancels. The second re-runs the cacheable Apex wire, because updateRecord updates Lightning Data Service but not the Apex result that fills the table.
Exercise
Why does the Name column in this chapter lack editable: true, and what would you change in the Apex query and column definitions to let users edit a contact's name?
Show answer
Name on Contact is a compound field built from FirstName and LastName, and updateRecord cannot write it. To support editing, add FirstName and LastName to the SELECT in getContacts, replace the Name column with two columns using fieldName: 'FirstName' and fieldName: 'LastName', and set editable: true on both.
Exercise
Your save handler uses Promise.all, and one of five updates fails because of a validation rule. Describe what the user sees and what a better handler would do.
Show answer
The other four updates still run and likely succeed, but the handler goes to the catch block, so all five drafts remain in the table. The user may think nothing was saved and may resubmit the four successful rows. A better handler uses Promise.allSettled, finds the rejected results, and sets draftValues to only the drafts that failed, then refreshes the wired data so the saved rows show their new values.