Edit a Record

The simplest way to create a form that enables you to edit a record is to use lightning-record-form. To customize the form layout or preload custom values, use lightning-record-edit-form.

If you need more flexibility than these components provide, see Build Custom UI to Create and Edit Records.

Tip

Edit a Record with Fields from a Layout Using lightning-record-form 

To edit a record, use the record-id and object-api-name attributes. When you provide a record ID, the component uses view mode by default, which displays output fields with edit icons. If you click an edit icon, all updateable fields in the form become editable. The editable form displays a Save button that updates the record, and a Cancel button that reverts changes.

The component provides default submit and error handlers. Errors are automatically displayed at the top of the form.

This example creates a form that lets users update fields from the compact layout on an account record. It displays the fields in a two-column layout.

1<template>
2  <lightning-record-form
3    record-id={recordId}
4    object-api-name={objectApiName}
5    columns="2"
6    mode="edit"
7    layout-type="Compact"
8  >
9  </lightning-record-form>
10</template>

To improve performance, specify fields instead of a layout whenever possible. Specify a layout only when you want the administrator, not the component, to control the fields that are provisioned. The component must handle receiving every field that is assigned to the layout for the context user.

Note

Place this example on a record page to inherit its record-id and object-api-name properties.

1import { LightningElement, api } from "lwc";
2export default class MyComponent extends LightningElement {
3  @api recordId;
4  @api objectApiName;
5}

You can override the default form behavior using custom events, such as displaying a toast when the submission succeeds or fails. For more information, see the lightning-record-form reference documentation.

Edit a Record with Specific Fields Using lightning-record-form 

You can specify which fields appear on the editable form, either by providing an array of field names or importing references to the fields.

Passing in the object and fields using strings doesn’t provide compile-time validation. You don’t know if the fields are valid until runtime. We recommend importing references to objects and fields from @salesforce/schema.

Note

This example uses the recordFormStaticContact component in the github.com/trailheadapps/lwc-recipes repo. It displays an editable form for a record using a static schema definition.

1<template>
2  <lightning-record-form
3    object-api-name={objectApiName}
4    record-id={recordId}
5    fields={fields}
6  ></lightning-record-form>
7</template>

Import the field references in your JavaScript file.

1import { LightningElement, api } from "lwc";
2
3import ACCOUNT_FIELD from "@salesforce/schema/Contact.AccountId";
4import NAME_FIELD from "@salesforce/schema/Contact.Name";
5import TITLE_FIELD from "@salesforce/schema/Contact.Title";
6import PHONE_FIELD from "@salesforce/schema/Contact.Phone";
7import EMAIL_FIELD from "@salesforce/schema/Contact.Email";
8
9export default class RecordFormStaticContact extends LightningElement {
10  // Flexipage provides recordId and objectApiName
11  @api recordId;
12  @api objectApiName;
13
14  fields = [ACCOUNT_FIELD, NAME_FIELD, TITLE_FIELD, PHONE_FIELD, EMAIL_FIELD];
15}

Edit a Record with a Custom Layout Using lightning-record-edit-form 

To provide a custom layout for your form fields, use the lightning-record-edit-form component. Pass in the fields to lightning-input-field, which displays an input control based on the record field type. This example displays several fields using a custom layout. Add this example component to a contact record page to inherit its record-id and object-api-name properties.

1<template>
2  <lightning-record-edit-form object-api-name="{objectApiName}" record-id="{recordId}">
3    <lightning-messages></lightning-messages>
4    <div class="slds-grid">
5      <div class="slds-col slds-size_1-of-2">
6        <lightning-input-field field-name="Name"></lightning-input-field>
7        <lightning-input-field field-name="Title"></lightning-input-field>
8      </div>
9      <div class="slds-col slds-size_1-of-2">
10        <lightning-input-field field-name="Phone"></lightning-input-field>
11        <lightning-input-field field-name="Email"></lightning-input-field>
12      </div>
13    </div>
14    <div class="slds-m-top_medium">
15      <lightning-button type="submit" variant="brand" label="Edit Contact"></lightning-button>
16    </div>
17  </lightning-record-edit-form>
18</template>

lightning-record-edit-form handles form submission and errors automatically. To display an error message above or below the form fields automatically, include lightning-messages before or after your lightning-input-field components.

Reset the Form to the Original Field Values 

lightning-record-edit-form doesn’t provide its own Cancel and Save buttons like lightning-record-form does. To create your own Cancel button that reverts the field values, include a lightning-button component that calls the reset() method. Replace the record-id with your own, or place this example on a contact record page to inherit its record-id property.

1<template>
2  <lightning-record-edit-form record-id={recordId} object-api-name="Contact">
3    <lightning-messages></lightning-messages>
4    <lightning-input-field field-name="FirstName"></lightning-input-field>
5    <lightning-input-field field-name="LastName"></lightning-input-field>
6    <lightning-input-field field-name="Email"></lightning-input-field>
7    <lightning-input-field field-name="Phone"></lightning-input-field>
8    <div class="slds-align_absolute-center slds-p-around_medium">
9      <lightning-button
10        class="slds-m-around_xx-small"
11        label="Cancel"
12        onclick={handleReset}
13      ></lightning-button>
14      <lightning-button
15        class="slds-m-around_xx-small"
16        label="Create Contact"
17        type="submit"
18        variant="brand"
19      ></lightning-button>
20    </div>
21  </lightning-record-edit-form>
22</template>

Call the reset() method on the lightning-input-field component.

1import { LightningElement, api } from "lwc";
2
3export default class FormResetExample extends LightningElement {
4  @api recordId;
5
6  handleReset(event) {
7    const inputFields = this.template.querySelectorAll("lightning-input-field");
8    if (inputFields) {
9      inputFields.forEach((field) => {
10        field.reset();
11      });
12    }
13  }
14}

Override Default Behaviors Using Custom Events 

lightning-record-edit-form handles form submission and errors automatically. To display an error message above or below the form fields automatically, include lightning-messages before or after your lightning-input-field components.

lightning-record-edit-form enables you to handle the following custom events.

  • error—Fired when the form returns a server-side error.
  • load—Fired when the form loads record data.
  • submit—Fired when the form is submitted.
  • success—Fired when the form data saves successfully.

This example displays a toast when an error occurs on form submission. Common errors include no network access or a required field is missing from the form. Use your own record ID or place the example on a contact record page to inherit its record ID.

1<template>
2  <lightning-record-edit-form
3    record-id={recordId}
4    object-api-name="Contact"
5    onerror={handleError}
6  >
7    <!--lightning-messages not needed here
8                since we’re displaying a toast with the error message -->
9    <!--<lightning-messages></lightning-messages>-->
10    <lightning-input-field field-name="FirstName"></lightning-input-field>
11    <lightning-input-field field-name="LastName"></lightning-input-field>
12    <lightning-input-field field-name="Email"></lightning-input-field>
13    <lightning-input-field field-name="Phone"></lightning-input-field>
14    <lightning-button type="submit" variant="brand" label="Create Contact"></lightning-button>
15  </lightning-record-edit-form>
16</template>

To display a toast, import the lightning/platformShowToastEvent module.

1import { LightningElement, api } from "lwc";
2import { ShowToastEvent } from "lightning/platformShowToastEvent";
3
4export default class FormErrorExample extends LightningElement {
5  @api recordId;
6
7  handleError(event) {
8    console.log(event.detail);
9    this.dispatchEvent(
10      new ShowToastEvent({
11        title: "Error creating record",
12        message: event.detail.message,
13        variant: "error",
14      }),
15    );
16  }
17}

event.detail.message returns a general description of the error. To return field-specific errors such as an error from a validation rule, use event.detail.output.fieldErrors, which provides a list of fields and record exception errors.

Let’s say you encounter validation rule errors in the FirstName, LastName, and Email fields, event.detail.output.fieldErrors can return something like this.

1{
2  "Email": [
3    {
4      "constituentField": null,
5      "duplicateRecordError": null,
6      "errorCode": "FIELD_CUSTOM_VALIDATION_EXCEPTION",
7      "field": "Email",
8      "fieldLabel": "Email",
9      "message": "Enter a Salesforce email"
10    }
11  ],
12  "Name": [
13    {
14      "constituentField": "FirstName",
15      "duplicateRecordError": null,
16      "errorCode": "FIELD_CUSTOM_VALIDATION_EXCEPTION",
17      "field": "Name",
18      "fieldLabel": "First Name",
19      "message": "Your first name should contain at least 2 characters"
20    },
21    {
22      "constituentField": "LastName",
23      "duplicateRecordError": null,
24      "errorCode": "FIELD_CUSTOM_VALIDATION_EXCEPTION",
25      "field": "Name",
26      "fieldLabel": "Last Name",
27      "message": "Your last name should contain at least 2 characters"
28    }
29  ]
30}

For more information, see the lightning-record-edit-form reference documentation.

Edit a Record with Custom Validation Using lightning-record-edit-form 

We recommend that you create validation rule errors to enforce field validation using lightning-input-field nested in lightning-record-edit-form, as discussed in Override Default Behaviors Using Custom Events.

lightning-input-field doesn’t support client-side custom validation. If you want to implement your own client-side validation, consider using lightning-input nested in lightning-record-edit-form instead.

Place this example on an account record page. This example wires up a lightning-input component to the Name field for editing.

1<!-- recordEditFormStaticAccount.html -->
2<template lwc:if={account.data}>
3  <lightning-record-edit-form
4    object-api-name={objectApiName}
5    record-id={recordId}
6    onsubmit={handleSubmit}
7  >
8    <lightning-input
9      label="Name"
10      value={name}
11      onchange={handleChange}
12      class="slds-m-bottom_x-small"
13    ></lightning-input>
14
15    <lightning-button class="slds-m-top_small" type="submit" label="Update Account Name">
16    </lightning-button>
17  </lightning-record-edit-form>
18</template>

Wire up the lightning-input component to the Salesforce field using the getRecord wire adapter and provide your own label. The wiring is done automatically when you use lightning-input-field, but not when you use lightning-input. Submit the record data using the onsubmit event handler on lightning-record-edit-form. In the event handler, perform the validation check using setCustomValidity() and update the fields with the user input value.

1// recordEditFormStaticAccount.js
2import { LightningElement, api, wire } from "lwc";
3import { getRecord } from "lightning/uiRecordApi";
4
5const FIELDS = ["Account.Name"];
6
7export default class RecordEditFormStaticAccount extends LightningElement {
8  @api recordId;
9  @api objectApiName;
10  inputVal = "";
11
12  @wire(getRecord, { recordId: "$recordId", fields: FIELDS })
13  account;
14
15  get name() {
16    return this.account.data.fields.Name.value;
17  }
18
19  handleChange(event) {
20    this.inputVal = event.target.value;
21  }
22
23  handleSubmit(event) {
24    event.preventDefault();
25    const inputCmp = this.template.querySelector("lightning-input");
26    const value = inputCmp.value;
27    // perform validation check
28    if (!value.includes("Burlington")) {
29      inputCmp.setCustomValidity("The account name must include 'Burlington'");
30    } else {
31      // if there was a custom error before, reset it
32      inputCmp.setCustomValidity("");
33      const fields = event.detail.fields;
34      fields.Name = this.inputVal;
35      this.template.querySelector("lightning-record-edit-form").submit(fields);
36    }
37    // shows the error right away without user interaction
38    inputCmp.reportValidity();
39  }
40}

lightning-input provides attributes for custom validation, such as min, max, and pattern. For more information, see the lightning-input reference documentation.

lightning-input-field is the preferred component to use with lightning-record-edit-form. Use lightning-input with lightning-record-edit-form only if validation rule errors don’t meet your requirements.

Note