Sub topic 6
Responding to success, error, submit and cancel
This chapter covers the events that lightning-record-form fires while a user saves a record. It assumes you can build a basic LWC with templates, @api properties and event handlers. It also assumes you know what a record ID is and have used lightning-record-form in view or edit mode. You should know how fields and layout-type pick the fields to show.
Why events matter
lightning-record-form saves records through Lightning Data Service, so you never write Apex or call a save method. The form still needs to tell your component what happened. It does this with DOM events. You listen with on attributes in the template, such as onsuccess={handleSuccess}.
The events used in this chapter are:
| Event | Fires when | Useful detail |
|---|---|---|
| `load` | The form has loaded the record data | `event.detail.records` |
| `submit` | The user clicks Save, before the save is sent | `event.detail.fields` |
| `success` | The record was saved | `event.detail.id` and `event.detail.fields` |
| `error` | The save failed | `event.detail.message` and `event.detail.detail` |
| `cancel` | The user clicks Cancel in edit mode | None |
The cancel and submit events are only meaningful when the form is editable. In view mode there is no Save or Cancel button, so those events do not fire.
The order of events
A normal save runs in a fixed order. The component fires submit first. If nothing stops it, the record is sent to the server. Then either success or error fires.
Cancel is a separate path. Clicking Cancel fires cancel and nothing is saved.
Handling success
The success event is the right place to confirm the save to the user. The event detail holds the ID of the saved record. This matters most when you create a record, because the ID does not exist until the save finishes.
Start with the template. The form has no record-id, so it creates a new Account.
<template>
<lightning-record-form
object-api-name="Account"
fields={fields}
onsuccess={handleSuccess}
onerror={handleError}
oncancel={handleCancel}>
</lightning-record-form>
</template>The class defines the fields and the three handlers.
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';
export default class AccountCreate extends LightningElement {
fields = [NAME_FIELD, INDUSTRY_FIELD];
handleSuccess(event) {
const recordId = event.detail.id;
this.dispatchEvent(
new ShowToastEvent({
title: 'Account created',
message: 'Record ID: ' + recordId,
variant: 'success'
})
);
}
handleError(event) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Save failed',
message: event.detail.message,
variant: 'error'
})
);
}
handleCancel() {
this.dispatchEvent(new CustomEvent('close'));
}
}A few points about this code:
ShowToastEventcomes fromlightning/platformShowToastEvent. It works in Lightning Experience and the Salesforce mobile app. Outside those containers, such as in Lightning Out, the toast may not appear.event.detail.idis the ID of the saved record. After an edit it is the same ID the form already had.- The
closeevent inhandleCancelis a custom event. A parent component that hosts this form, for example in a modal, can listen for it and hide the form.
Handling errors
Without an error handler, lightning-record-form still shows failures inline. It displays a message at the top of the form and marks the fields that caused the problem. For many forms that is enough.
You add onerror when you need to do something extra, such as log the failure, show a toast, or re-enable a button in a surrounding component.
The error event detail has two parts:
event.detail.messageis a short summary, such as "An error occurred while trying to update the record. Please try again."event.detail.detailis a longer explanation. It is often the text of a validation rule or a duplicate rule.
Field-level problems arrive in event.detail.output.fieldErrors. Page-level problems arrive in event.detail.output.errors. These properties are not always present, so guard against missing values.
handleError(event) {
const detail = event.detail || {};
const fieldErrors = (detail.output && detail.output.fieldErrors) || {};
const fieldNames = Object.keys(fieldErrors);
const message = fieldNames.length
? 'Check these fields: ' + fieldNames.join(', ')
: detail.message;
this.dispatchEvent(
new ShowToastEvent({
title: 'Save failed',
message,
variant: 'error'
})
);
}Intercepting submit
The submit event fires after the user clicks Save and before the data leaves the browser. Its detail contains the field values the form is about to save, in event.detail.fields.
You have two choices in a submit handler:
- Read the values and let the save continue.
- Call
event.preventDefault()to stop the save, then decide what to do.
On lightning-record-form, preventDefault() cancels the save. Use it when you want to reject a value in your own code. You can show your own message and leave the form open.
<template>
<lightning-record-form
object-api-name="Account"
fields={fields}
onsubmit={handleSubmit}
onsuccess={handleSuccess}>
</lightning-record-form>
</template>handleSubmit(event) {
const fields = event.detail.fields;
const name = (fields.Name || '').trim();
if (name.length < 3) {
event.preventDefault();
this.dispatchEvent(
new ShowToastEvent({
title: 'Name too short',
message: 'Enter at least three characters.',
variant: 'warning'
})
);
}
}If the name passes the check, the handler does nothing and the form saves as usual. The same keys appear in fields as the API names of the fields on the form, for example Name and Industry.
Handling cancel
In edit mode, the Cancel button fires cancel. By default the form handles it itself. It discards the edits and returns to view mode when the form was in view mode first. In a create form there is no record to go back to, so the form simply clears.
You listen to oncancel when the surrounding page needs to react. A common case is a modal that holds the form. Cancel should close the modal, not only reset the fields.
handleCancel() {
this.dispatchEvent(new CustomEvent('close'));
}Cancel does not produce a success or error event. Do not rely on those two events to clean up after a cancelled form.
Handling load
The load event fires once the form has fetched the record and is ready. Use it to read the loaded values or to stop a loading indicator that you started yourself.
handleLoad(event) {
const records = event.detail.records;
const recordId = this.recordId;
const account = records[recordId];
console.log(account.fields.Name.value);
}The records object is keyed by record ID. Each entry has a fields map, and each field has a value and a displayValue. For a create form without a record-id, there is no record to read, so check that your key exists before you use it.
Common mistakes
- Reading the wrong ID. Use
event.detail.idinsuccess, notthis.recordId. On a create form,this.recordIdis empty. - Expecting a changed value to be saved. Changing
event.detail.fieldsinside arecord-formsubmit handler does not change what is saved. - Forgetting that errors can lack detail. Access
event.detail.outputwith a guard, because it is not set for every failure. - Using
cancelfor cleanup of saved data. Nothing is saved when it fires, so there is nothing to undo on the server. - Dispatching a toast in a context that does not show it. Test in the container where your component will run.
Putting it together
A good record form handler set is small. It confirms success with the record ID, reports errors in one place, lets simple validation block a save through preventDefault(), and tells its parent when the user cancels. When you need to change values before saving, move to lightning-record-edit-form.
Exercise
A create form uses lightning-record-form with no record-id. In the success handler you write this.recordId to get the new record's ID, and it is undefined. What should you use instead, and why?
Show answer
Use event.detail.id. The component's recordId property was never set because the form had no record when it started. The success event reports the ID of the record that was just created.
Exercise
You want to stop a save when the Name field has fewer than three characters, without losing what the user typed. Which event and method do you use?
Show answer
Handle the submit event and call event.preventDefault() when the check fails. The save does not happen, the form stays open, and the entered values remain in the fields.
Exercise
Why is lightning-record-form a poor choice if you must trim whitespace from LastName before every save?
Show answer
Its submit handler can only allow or block the save. It cannot replace the values that get saved. Use lightning-record-edit-form, call event.preventDefault(), change the fields, and then call submit(fields) on the form.