Create a Record
The simplest way to create a form that enables a user to create a record is to use lightning-record-form
. To customize the form layout or to 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.
To create a record using lightning-record-form
, leave out the record-id
attribute. This example creates a record using import references for the account object and its fields. The form displays a Save button that updates the record, and a Cancel button that reverts changes.
The field imports are passed in to the myFields
array. When you import references, the references are validated at compile time. Place this example on a record page to inherit its record-id
and object-api-name
properties.
When data saves successfully, the fields display pencil icons to denote that inline editing is available. This view is displayed until you refresh or reload the page.
Use lightning-record-edit-form
to customize field layout or data rendering.
Pass in the fields you want to lightning-input-field
, which displays an input control based on the record field type. To enable automatic display of error messages, include the lightning-messages
component.
To access the fields you want, use the field imports from @salesforce/schema
. Importing references to objects and fields ensures that your code works, even when object and field names change.
To provide a field value when the form displays, use the value
attribute on lightning-input-field
.
This example displays a form with a custom value for the account name field. The form creates an account record when the button is clicked.
To programmatically set the value when the form loads, provide the value in JavaScript. This example sets the value using the myValue
property. You can set this value programmatically later, as shown by the onclick
event handler, which calls the overrideValue
method.
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. For an example, see Edit a Record.
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 submits changed record data.success
—Fired when the form submits changed record data.
For an example, see Edit a Record.