Sub topic 9
Record forms with lightning-record-edit-form
This chapter covers building a create or edit form with lightning-record-edit-form and lightning-input-field. It assumes you know the structure of a Lightning web component (template, JavaScript class, CSS file) and have met lightning-input and the event model from earlier chapters. You need an org or scratch org to try the examples.
What the component does
lightning-record-edit-form is a base component that wraps a set of fields for one record of one object. It uses Lightning Data Service (LDS), the Salesforce layer that reads and writes records for components. Because of that, you don't write Apex to save a record, and the form respects field-level security and object permissions for the current user.
The form relies on three things:
lightning-record-edit-form, the container. It owns the record context and the save.lightning-input-field, a field inside the form. It picks the right input control from the field's metadata (text box, date picker, picklist, lookup, and so on).lightning-messages, an optional element that shows errors returned by the save.
Compare this with lightning-input. A lightning-input is a generic control. You choose its type, wire its value to your JavaScript, and validate it yourself. A lightning-input-field is bound to a field on an object, so it already knows the label, the data type, the picklist values, and whether the field is required.
A minimal create form
The form below creates a Contact.
<template>
<lightning-record-edit-form object-api-name="Contact" onsuccess={handleSuccess}>
<lightning-messages></lightning-messages>
<lightning-input-field field-name="FirstName"></lightning-input-field>
<lightning-input-field field-name="LastName"></lightning-input-field>
<lightning-button
class="slds-m-top_small"
type="submit"
variant="brand"
label="Save"
></lightning-button>
</lightning-record-edit-form>
</template>Four details matter here:
object-api-nametells the form which object to create. Without arecord-id, the form is in create mode.- The button has
type="submit". Clicking it submits the form, and the form saves the values of all itslightning-input-fieldchildren. You don't write a click handler. lightning-messagesdisplays save errors, such as a validation rule failure, without code from you.onsuccessruns after the record is saved.
The success handler receives the new record's ID in event.detail.id.
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class ContactCreate extends LightningElement {
handleSuccess(event) {
const recordId = event.detail.id;
this.dispatchEvent(
new ShowToastEvent({
title: 'Contact created',
message: `Record ${recordId} was saved.`,
variant: 'success'
})
);
}
}Edit mode
To edit an existing record, set record-id. The form loads the record and fills each field.
<template>
<lightning-record-edit-form
object-api-name="Contact"
record-id={recordId}
onsuccess={handleSuccess}
>
<lightning-messages></lightning-messages>
<lightning-input-field field-name="FirstName"></lightning-input-field>
<lightning-input-field field-name="LastName"></lightning-input-field>
<lightning-input-field field-name="Email"></lightning-input-field>
<lightning-button type="submit" variant="brand" label="Update"></lightning-button>
</lightning-record-edit-form>
</template>import { LightningElement, api } from 'lwc';
export default class ContactEdit extends LightningElement {
@api recordId;
handleSuccess() {
// The form has already saved the changes at this point.
}
}When a component is placed on a record page, the platform sets recordId for you if you declare it with @api. In edit mode you can also omit object-api-name. Keep it anyway, since it makes the intent clear and is required for create.
How the form works internally
The form is a small state machine. Fields start empty (create) or load from LDS (edit). The user edits values. On submit, the form collects field values and asks LDS to save. LDS either returns the record or returns errors.
Each stage has an event you can hook:
| Event | When it fires | Useful for |
|---|---|---|
| `onload` | After record data and metadata load | Reading initial values |
| `onsubmit` | When the user submits, before the save | Changing field values, custom validation |
| `onsuccess` | After a successful save | Toasts, navigation, notifying a parent |
| `onerror` | After a failed save | Custom error handling |
Changing values before the save
The submit event carries the fields about to be saved in event.detail.fields. To change them, cancel the default submit and call the form's submit() method with the new fields.
<template>
<lightning-record-edit-form
object-api-name="Contact"
onsubmit={handleSubmit}
onsuccess={handleSuccess}
>
<lightning-messages></lightning-messages>
<lightning-input-field field-name="FirstName"></lightning-input-field>
<lightning-input-field field-name="LastName"></lightning-input-field>
<lightning-button type="submit" variant="brand" label="Save"></lightning-button>
</lightning-record-edit-form>
</template>import { LightningElement } from 'lwc';
export default class ContactCreateTrimmed extends LightningElement {
handleSubmit(event) {
event.preventDefault();
const fields = { ...event.detail.fields };
fields.LastName = (fields.LastName || '').trim().toUpperCase();
this.refs.form.submit(fields);
}
handleSuccess(event) {
console.log('Saved', event.detail.id);
}
}For this.refs.form to work, add lwc:ref="form" to the form element in the template. The older approach is this.template.querySelector('lightning-record-edit-form'), which also works. Either way, call preventDefault() first. Otherwise the form saves the original values and your call saves a second time.
Values that are not on the form
Sometimes a field must be set but the user should not see it. An example is a Contact's AccountId when the form sits on an Account page. Pass it through the fields object in the submit() call:
handleSubmit(event) {
event.preventDefault();
const fields = { ...event.detail.fields, AccountId: this.recordId };
this.refs.form.submit(fields);
}You can also add a lightning-input-field with a value attribute and hide it with the slds-hide class. The submit() approach is cleaner, because the value does not depend on the DOM.
Validation and errors
Errors come from three places:
- Client-side field checks. Required fields, such as
LastNameon Contact, show an inline message and block the save before any request is made. - Server-side checks. Validation rules, triggers, and duplicate rules reject the save.
lightning-messagesshows them at the top of the form, andonerrorfires. - Permissions. If the user can't edit a field,
lightning-input-fieldrenders it read-only or not at all, depending on field-level security.
If you want your own error display, handle onerror and read event.detail:
handleError(event) {
const detail = event.detail;
console.error(detail.message, detail.output && detail.output.errors);
}Without lightning-messages, server errors that aren't tied to a field are not shown to the user. This is a common bug: the Save button seems to do nothing. Include lightning-messages unless you replace it with your own handling.
Layout and styling
The form has no layout of its own. Its children stack vertically in the order you write them. To arrange fields, put them in the SLDS grid from the earlier chapter.
<template>
<lightning-record-edit-form object-api-name="Contact">
<lightning-messages></lightning-messages>
<div class="slds-grid slds-gutters slds-wrap">
<div class="slds-col slds-size_1-of-1 slds-medium-size_1-of-2">
<lightning-input-field field-name="FirstName"></lightning-input-field>
</div>
<div class="slds-col slds-size_1-of-1 slds-medium-size_1-of-2">
<lightning-input-field field-name="LastName"></lightning-input-field>
</div>
</div>
<lightning-button type="submit" variant="brand" label="Save"></lightning-button>
</lightning-record-edit-form>
</template>Fields inside plain div elements still belong to the form, because the form finds its fields through the DOM tree below it. A lightning-input-field placed outside the form, or inside a child custom component, is not part of the save. This is a second common error. If a field in a child component is not saved, move it into the same template as the form.
Choosing among form components
lightning-record-edit-form is one of three record form components built on LDS.
| Component | Layout | Customization | Use when |
|---|---|---|---|
| `lightning-record-form` | Automatic, from fields list or page layout | Low | You want a working form with the least markup |
| `lightning-record-edit-form` | You write it | High | You need field order, grid layout, custom buttons, or logic on submit |
| `lightning-record-view-form` | You write it | High | You need a read-only display with the same field components |
If you need to save data that isn't a single record, or to compose several objects in one transaction, none of these fit. Use lightning/uiRecordApi functions or Apex instead.
Common mistakes
- Using
lightning-inputinside the form and expecting it to save. Onlylightning-input-fieldparticipates. - Using a button without
type="submit". It will not submit the form. - Forgetting
lightning-messages, which hides server errors. - Calling
submit(fields)withoutpreventDefault(), causing a double save. - Wrong API names. Custom fields need the
__csuffix, such asRating__c. A wrong name produces a console error and an empty field. - Importing field references is the safer approach for fields in code. In markup you can pass a plain string, but in JavaScript you can import a schema reference such as
import LASTNAME_FIELD from '@salesforce/schema/Contact.LastName';and useLASTNAME_FIELD.fieldApiName. This lets the platform check that the field exists at deploy time.
Exercises
Exercise
A developer adds a lightning-record-edit-form with two lightning-input-field elements and a lightning-button with label="Save" and no type. Clicking Save does nothing. What is the fix?
Show answer
Add type="submit" to the button. Only a submit button triggers the form's save. No click handler is needed.
Exercise
You want to store LastName in upper case. Which handler and calls do you use, and what mistake causes two records to be created?
Show answer
Handle onsubmit, call event.preventDefault(), copy event.detail.fields, change LastName, and call submit(fields) on the form. Skipping preventDefault() lets the default save run as well, so the record is saved twice.
Exercise
A Contact form shows a Save button, but when a validation rule fails the user sees nothing. What is missing, and what event can you use to build your own message?
Show answer
The form has no lightning-messages element. Add it, or handle onerror and read event.detail.