Build Custom UI to Create and Edit Records
If the lightning-record*form
components don’t provide enough flexibility for your use case, use the JavaScript API to build UI that creates and edits records.
Before you use the JavaScript API, see whether the lightning-record*form
components meet your needs. See Compare Base Components.
This document explains the ldsCreateRecord
component in the lwc-recipes repo. The component asks for a name and creates an account with that name. When the account is created, it renders the account Id.
To create a record via JavaScript, call the createRecord()
function. This component calls the function in the createAccount
handler.
The component’s JavaScript imports createRecord
from the lightning/uiRecordApi
module. To display notifications for error handling, it imports ShowToastEvent
from lightning/platformShowToastEvent
. It also imports references to the Account object and Account name field.
Specify the apiName
and fields
values for your recordInput
object. In the example, we pass in fields
on the recordInput
object using a shorthand syntax, instead of passing in fields: fields
. Then, pass the account name to createRecord(recordInput)
, which creates an account record based on the name you provide.
Next, provide a handler that creates an account record using createRecord(recordInput)
. In this example, the handleNameChange(event)
method handles a change
event from the component HTML file when a user enters an account name.
The createRecord(recordInput)
function returns a Promise object that resolves when the record is created. This component returns the account.id
and sets it to the accountId
property. If an error is returned in the async function, the promise is rejected. You can handle the error using the try/catch block.
To update a record, see updateRecord(recordInput, clientOptions). To update multiple records using Apex, see Display Data in a Table with Inline Editing.
See Also