Sub topic 9
Handling load, success and error events
This chapter covers the three events that lightning-record-edit-form fires around loading and saving a record: load, success and error. It assumes you can already build a basic lightning-record-edit-form with lightning-input-field and lightning-messages, and that you know how LWC event handlers receive an event object.
The save lifecycle
A record edit form fires a small set of events in a fixed order. Knowing the order tells you which handler is the right place for each piece of logic.
onloadfires after the form has its record and object metadata.onsubmitfires when the user clicks the submit button. The next chapter covers it in detail.onsuccessfires after Lightning Data Service has saved the record.onerrorfires when the save is rejected.
Only one of success and error fires for a given save attempt.
A form that wires all three events
The template below edits an existing Account and binds all three handlers. The record-id attribute comes from the @api recordId property, which is set automatically when the component sits on a record page.
<template>
<lightning-record-edit-form
object-api-name="Account"
record-id={recordId}
onload={handleLoad}
onsuccess={handleSuccess}
onerror={handleError}>
<lightning-messages></lightning-messages>
<lightning-input-field field-name="Name"></lightning-input-field>
<lightning-input-field field-name="Industry"></lightning-input-field>
<lightning-input-field field-name="Phone"></lightning-input-field>
<lightning-button
class="slds-m-top_small"
type="submit"
label="Save">
</lightning-button>
</lightning-record-edit-form>
</template>The lightning-messages element is what shows server-side errors inside the form. It does not depend on your onerror handler. If you handle error and also keep lightning-messages, the user sees the message twice, once inline and once in your toast. Pick one place for the message, or make the toast carry something different, such as a short summary.
Handling the load event
The load event gives you the record data the form fetched. In event.detail.records, each record is keyed by its ID. Each record has a fields object, and each field has a value and a displayValue.
import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class AccountEdit extends LightningElement {
@api recordId;
originalName;
handleLoad(event) {
const record = event.detail.records[this.recordId];
if (record) {
this.originalName = record.fields.Name.value;
}
}
handleSuccess(event) {
const updatedId = event.detail.id;
this.dispatchEvent(
new ShowToastEvent({
title: 'Account saved',
message: 'Record ID: ' + updatedId,
variant: 'success'
})
);
}
handleError(event) {
const detail = event.detail;
this.dispatchEvent(
new ShowToastEvent({
title: detail.message || 'Save failed',
message: detail.detail || 'Check the highlighted fields and try again.',
variant: 'error',
mode: 'sticky'
})
);
}
}Common uses of load:
- Keeping a copy of the original values, for example to detect whether the user changed anything.
- Reading a field the user cannot see on the form, as long as that field is included in the form.
- Hiding a loading spinner you showed while the form was fetching data.
Some points about load that cause bugs:
event.detail.recordsonly contains fields the form requested. A field appears there only if you placed alightning-input-fieldorlightning-output-fieldfor it on the form.- The record key is the 15- or 18-character ID as the platform returns it. Index with the same ID you passed in
record-id, and guard againstundefinedas the example does. - When the form has no
record-id(create mode), there is no existing record to read. Do not write code that assumesrecordsholds data. - A field the user cannot read because of field-level security is missing from the data. Check for it before reading
.value.
Handling the success event
success fires after the record is saved. The detail includes the following properties:
| Property | Contents |
|---|---|
| `id` | The ID of the created or updated record |
| `apiName` | The object API name, such as `Account` |
| `fields` | The saved field values, in the same shape as `load` |
| `recordTypeInfo` | Record type information, when the object has record types |
The most common use is reading event.detail.id after a create, because the ID does not exist until the save finishes. Typical follow-up actions are:
- Showing a success toast.
- Navigating to the new record with
NavigationMixin. - Clearing the form so the user can enter another record.
- Telling a parent component with a custom event.
To clear a create form, reset the input fields explicitly. lightning-input-field supports a reset() method:
handleSuccess(event) {
const inputFields = this.template.querySelectorAll('lightning-input-field');
if (inputFields) {
inputFields.forEach((field) => field.reset());
}
this.dispatchEvent(
new CustomEvent('contactcreated', { detail: { id: event.detail.id } })
);
}On an edit form, reset() restores the values the record had when it loaded. After a successful save, those values are the new saved ones, so resetting an edit form after success has no visible effect.
Handling the error event
error fires when the save fails. The event detail has these properties:
message: a summary of the failure.detail: a longer explanation, which can be empty.output.errors: an array of record-level errors, such as failures from validation rules or Apex triggers.output.fieldErrors: an object keyed by field API name, with the errors for each field.
A handler that surfaces field-level problems looks like this:
handleError(event) {
const output = event.detail.output || {};
const fieldErrors = output.fieldErrors || {};
const lines = [];
Object.keys(fieldErrors).forEach((fieldName) => {
fieldErrors[fieldName].forEach((err) => {
lines.push(fieldName + ': ' + err.message);
});
});
(output.errors || []).forEach((err) => lines.push(err.message));
this.dispatchEvent(
new ShowToastEvent({
title: 'Save failed',
message: lines.join('\n') || event.detail.message,
variant: 'error'
})
);
}Errors that reach this event include:
- Required fields left empty.
- Validation rule failures.
- Duplicate rule blocks.
- A trigger that calls
addError. - Insufficient access, such as a user who lacks edit permission on the object.
error does not fire for problems that stop the form from submitting at all. If a lightning-input-field fails client-side checks, such as a required field left empty, the form shows the field's inline error and does not send the save, so submit may not fire either. If you override submit and call event.preventDefault() without ever calling submit(fields), neither success nor error fires, because no save happens.
Common mistakes
- Using the wrong ID after a create.
this.recordIdis empty on a create form. Readevent.detail.idinsuccess. - Duplicate messages. A toast plus
lightning-messagesrepeats the same text. Choose one. - Reading a field that was never on the form.
loadonly reports the fields the form uses. Add a hidden-by-stylelightning-input-fieldorlightning-output-field, or read the value withgetRecord. - Handler names without braces. Write
onsuccess={handleSuccess}. A string such asonsuccess="handleSuccess"does not bind the handler. - Assuming
fieldErrorsis always set. Record-level failures put their messages inoutput.errors, so check both.
Exercise
A create form for Contact shows a success toast that says "Saved record undefined". The handler reads this.recordId. What is wrong, and what should the handler read instead?
Show answer
On a create form there is no record-id, so this.recordId is undefined. The new record's ID only exists after the save, and it arrives as event.detail.id in the success event. Change the handler to use event.detail.id.
Exercise
Your load handler reads event.detail.records[this.recordId].fields.Description.value and throws an error, although the Account has a description. The form contains inputs for Name and Industry only. Why does it fail, and how can you fix it?
Show answer
The load event only includes fields the form requested, and Description is not on the form, so fields.Description is undefined. Add a lightning-input-field or lightning-output-field for Description (or load the value separately with getRecord), and guard the read in case the user lacks access to the field.