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.
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.
<lightning-record-edit-form record-id="002XXXXXXXXXXXXXXX" object-api-name="Account">
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.