Sub topic 3
Handling Record Form Events and Save Behavior
Assume you know LWC templates, event handlers, record IDs, and Salesforce objects and fields.
Handling load, success, and error events
Both lightning-record-form and lightning-record-edit-form dispatch events during the form lifecycle:
loadfires when record data is ready.successfires after a save succeeds.errorfires when security, validation, or server processing rejects a save.
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class ContactCreate extends LightningElement {
handleLoad() {
console.log('Form data loaded');
}
handleSuccess(event) {
this.dispatchEvent(new ShowToastEvent({
title: 'Saved',
message: `Record ${event.detail.id} was saved.`,
variant: 'success'
}));
}
handleError(event) {
this.dispatchEvent(new ShowToastEvent({
title: 'Save failed',
message: event.detail.message,
variant: 'error'
}));
}
}Bind these methods with onload, onsuccess, and onerror in the template. Add lightning-messages to an edit form when you want field-level messages displayed automatically.
Overriding submit
An edit form can intercept submission. Cancel the default event, validate or change event.detail.fields, then call submit yourself.
handleSubmit(event) {
event.preventDefault();
const fields = event.detail.fields;
fields.LastName = (fields.LastName || '').trim();
if (!fields.LastName) {
return;
}
this.template.querySelector('lightning-record-edit-form').submit(fields);
}Record types and form density
Use record-type-id when the form must use a specific record type. Density controls spacing and label placement where the component supports it. A compact layout can show more fields, while a comfortable layout improves readability.
Choosing and synchronizing components
Use lightning-record-form for a quick standard layout. Use lightning-record-edit-form when you need custom field order, custom buttons, or submit logic. Use lightning-record-view-form for a read-only custom layout.
Lightning Data Service usually keeps components using the same record current. Refresh Apex-wired data with refreshApex after a save. Components using other data sources may need their own refresh method.
Limitations and troubleshooting
- Missing fields often indicate layout, permission, or field-name problems.
- Validation errors appear in
error, notsuccess. - A missing
record-idcreates a record instead of editing one. - Stale data can result from Apex caching or a data source outside Lightning Data Service.
Exercise
Which component should you choose when you need a custom field order and must trim a value before saving?
Show answer
Use lightning-record-edit-form, intercept onsubmit, modify event.detail.fields, and call submit(fields).