Lightning Record Edit Form (LWC)

|
| By Webner

In Salesforce, LWC allows us to use lightning-record-edit-form which implements Lightning Data Service and doesn’t require any additional Apex controllers to create or update record data. It also takes care of field-level security and sharing for us, so that users can only see the data they are allowed to. We can use this to create or update records with Apex controllers can lead to unexpected behaviors. Moreover, data provisioned by Apex is not managed and we must handle data refresh by invoking the Apex method again on our own. It also handles field-level validation errors and Lightning Data Service errors automatically. A Lightning Data Service error is encountered when a resource becomes inaccessible on the server or any invalid record ID is passed. for example. To display the error message automatically, we need to add lightning-messages immediately before or after the lightning-input-field components.

Record Editing

To edit a record of an object, we need to pass in the ID of the record and the corresponding object API name to be edited. We also need to specify the fields that we want to include in the record edit layout using lightning-input-field. By passing the fields it will replicate all the validations which are given to the field of the object we don’t need to specify any of the validation.
Add a lightning-button component with type=”submit”, this will automatically save any changes in the input fields when the button is clicked.
<template>
<lightning-record-edit-form record-id="002XXXXXXXXXXXXXXX" object-api-name="Account">
<lightning-messages>
</lightning-messages>
<lightning-output-field field-name="Id">
</lightning-output-field>
<lightning-input-field field-name="FirstName">
</lightning-input-field>
<lightning-input-field field-name="LastName">
</lightning-input-field>
<lightning-button
variant="brand"
type="submit"
name="update"
label="Update">
</lightning-button>
</lightning-record-edit-form>
</template>

Record Creation

For creating a new record we need to only pass in the object API name for the record to be created. No record id is needed for creating a new record. We just need to specify the fields that we want to include in the new record layout using lightning-input-field components.
Include a lightning-button component with type=”submit” to automatically save the record when the button is clicked.
<template>
<lightning-record-edit-form object-api-name="Contact">
<lightning-messages>
</lightning-messages>
<lightning-input-field field-name="Name">
</lightning-input-field>
<lightning-button
type="submit"
label="Create new">
</lightning-button>
</lightning-record-edit-form>
</template>

Leave a Reply

Your email address will not be published. Required fields are marked *