Sub topic 7
Saving changes with updateRecord
This chapter covers how the screen action saves its changes. It assumes you can build a basic LWC and use @api properties. It also assumes you know how recordId reaches a record quick action, and that you have the lightning-quick-action-panel layout from the previous chapter. The component here updates the Description field on an Account.
Why updateRecord
A quick action that edits a record needs a way to write to the database. You have two main options in LWC:
- Call an Apex method imperatively.
- Use
updateRecordfromlightning/uiRecordApi.
updateRecord is a function from Lightning Data Service (LDS). LDS is the client-side layer that reads and writes records through the User Interface API. For a simple field change, updateRecord has three advantages over Apex:
- You write no server code and no test class.
- The platform enforces field-level security, object permissions, and sharing for you.
- LDS keeps a shared cache of records. When
updateRecordsucceeds, the cache entry is updated, and other components showing that record refresh without extra work.
Use Apex instead when the save involves several objects, callouts, or logic the User Interface API cannot express.
What updateRecord accepts and returns
The signature is updateRecord(recordInput, clientOptions). It returns a Promise.
recordInputis an object with afieldsproperty.fieldsmaps field API names to new values.fieldsmust includeId. Without it, the call rejects.clientOptionsis optional. ItsifUnmodifiedSincevalue is a timestamp used for conflict detection. If the record changed on the server after that time, the save fails.- On success, the Promise resolves with the updated record data.
- On failure, the Promise rejects with an error object.
Send only the fields you want to change. Every other field is left alone.
Importing field references
The sample code imports fields from @salesforce/schema instead of typing strings:
import ID_FIELD from '@salesforce/schema/Account.Id';
import DESCRIPTION_FIELD from '@salesforce/schema/Account.Description';Each import is a field reference object. Its fieldApiName property holds the API name, such as Description. There are three reasons to prefer imports over string literals:
- The deployment checks that the referenced field exists.
- The platform records a dependency, so someone cannot delete the field without noticing.
- Namespaced fields resolve correctly in managed packages.
The full save flow
The handleSave method from the screen action does five things in order:
- It sets
isSavingtotrue, which disables the Save button. - It builds the
fieldsobject with the record Id and the new description. - It awaits
updateRecord. - On success, it shows a toast and closes the panel.
- In a
finallyblock, it setsisSavingback tofalse.
import { LightningElement, api } from 'lwc';
import { CloseActionScreenEvent } from 'lightning/actions';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import ID_FIELD from '@salesforce/schema/Account.Id';
import DESCRIPTION_FIELD from '@salesforce/schema/Account.Description';
export default class UpdateDescription extends LightningElement {
@api recordId;
description = '';
isSaving = false;
handleChange(event) {
this.description = event.target.value;
}
handleCancel() {
this.dispatchEvent(new CloseActionScreenEvent());
}
async handleSave() {
this.isSaving = true;
const fields = {};
fields[ID_FIELD.fieldApiName] = this.recordId;
fields[DESCRIPTION_FIELD.fieldApiName] = this.description;
try {
await updateRecord({ fields });
this.dispatchEvent(new ShowToastEvent({
title: 'Success',
message: 'Description updated',
variant: 'success'
}));
this.dispatchEvent(new CloseActionScreenEvent());
} catch (error) {
this.dispatchEvent(new ShowToastEvent({
title: 'Error updating record',
message: error?.body?.message || 'Unknown error',
variant: 'error'
}));
} finally {
this.isSaving = false;
}
}
}The panel closes only on success. On failure it stays open, so the user keeps what they typed and can correct it.
Why the Save button is disabled while saving
The template binds disabled={isSaving} on the Save button. Without it, a user can click twice and send two updates. The second one is usually harmless for a single field update. It is not harmless if the save also triggers record-triggered flows or Apex triggers, because those run twice.
The finally block matters when the panel stays open. If you reset isSaving only in the success path, a failed save leaves the button disabled and the user has to cancel and start over.
Reading errors
The error from a rejected updateRecord is not an Error instance with a plain message. It is usually a FetchResponse-like object with a body property. Its shape depends on the failure:
| Failure | Where the details are |
|---|---|
| Validation rule or required-field failure | `error.body.output.fieldErrors`, keyed by field API name |
| Page-level or trigger error | `error.body.output.errors`, an array of objects with a `message` |
| Network or other server problem | `error.body.message` |
| Code bug in your component | `error.message` |
The sample uses error?.body?.message || 'Unknown error'. That is a reasonable first pass, but a validation rule failure often has an empty or generic body.message. The useful text sits in output. A small helper covers all the cases:
export function reduceErrors(error) {
if (!error) {
return ['Unknown error'];
}
const messages = [];
const output = error.body && error.body.output;
if (output) {
(output.errors || []).forEach((e) => messages.push(e.message));
Object.values(output.fieldErrors || {}).forEach((list) =>
list.forEach((e) => messages.push(e.message))
);
}
if (error.body && error.body.message) {
messages.push(error.body.message);
}
if (!messages.length && error.message) {
messages.push(error.message);
}
return messages.length ? messages : ['Unknown error'];
}In the catch block, call reduceErrors(error).join(', ') for the toast message.
What gets updated after a save
After a successful updateRecord, LDS updates its cache. Components on the page that use getRecord through @wire, and standard components such as the record detail panel, show the new value without a reload.
This does not cover everything:
- A component that loaded data through an Apex method has no link to LDS. It will not refresh on its own.
- Changes made by Apex, a flow, or a trigger that the cache never saw are also invisible to LDS. A trigger that updates a second field on the same record is a common example.
For those cases, call notifyRecordUpdateAvailable([{ recordId }]) from lightning/uiRecordApi. It tells LDS to re-fetch the record. Refreshing the view is covered in a later chapter.
Common problems
- Missing Id. Forgetting
ID_FIELDproduces a rejected Promise with a message about a missing record Id. Always include it. - Wrong field type. Sending a string to a number or date field returns a field error. Convert first, for example with
Number(value). - Overwriting existing data. The sample starts with an empty
descriptionand does not load the current value. A user who saves without typing erases the existing description. In real code, load the current value with@wire(getRecord)and use it as the initial text, or validate that the field is not empty. - Hardcoded object. The schema imports name
Account, so the component works only on Account records. For several objects, use separate components or build the field name fromobjectApiName. - No permission. If the user lacks edit access to the record or the field, the save fails with an insufficient access error. Show that message. Do not retry.
- Updating formula or read-only fields. The request is rejected. Check that the field is updateable before including it.
Choosing a save method
| Need | Choice |
|---|---|
| Change a few fields on one record | `updateRecord` |
| Create a new record | `createRecord` |
| Show a full edit form with built-in validation | `lightning-record-edit-form` |
| Change several records or run complex logic | Apex method called imperatively |
The quick action here uses a custom textarea and a custom Save button, so updateRecord fits. If the panel were a plain form of standard fields, lightning-record-edit-form would need less code.
Exercise
A screen action calls updateRecord({ fields: { Description: 'New text' } }) and the Promise rejects. The component has the record Id in this.recordId. What is the most likely cause, and how do you fix it? Also name one thing the finally block protects against in the sample code.
Show answer
The fields object has no Id, and updateRecord requires it to know which record to change. Fix it by adding the Id, for example fields[ID_FIELD.fieldApiName] = this.recordId. The finally block resets isSaving whether the save succeeds or fails. Without it, a failed save would leave the Save button disabled and the user could not retry.