Using lightning-record-edit-from in LWC

LDS helps us interact with data when there is a single record in question. Let's look at how to use lightning-edit-from in LWC.

It's very common for a Salesforce Developer to interact with data when working with Lightning Web Components.

And it's not going to be fair on Salesforce part to expect the developers to write 30-40 lines of code every time when there is some sort of interaction with the data.

So similar to Standard Controllers in Salesforce Classic there is something called Lightning Data Services in LWC.

But there is a catch we can only use it only when we want to interact with a single record.

LDS has got three tags that we can use when we want to interact with data and these are the tags

  • lightning-record-edit-form
  • lightning-record-view-form
  • lightning-record-form

In this post, we will be looking at lightning-record-edit-form.

In the below code if I don't provide `record-id` then I can use the same tag to create a new record. If recordId is provided then we can update the record.
<template>
	<lightning-record-edit-form 
    object-api-name="Account" 
	record-id={recordId}>
	<lightning-input-field field-nam="Name"></lightning-input-field>    
    <lightning-input-field field-nam="Industry"></lightning-input-field>    
	<lightning-input-field field-nam="Rating"></lightning-input-field>
	</lightning-record-edit-form>

</template>
lightning-record-edit-from used to load the record in edit mode

That's it!

There is no need to use any JavaScript methods involved etc. However, if you are interested in using it, nothing is stoping you.

You can use attributes like onsubmit, onsuccess and onerror.

<template>
	<lightning-record-edit-form 
    object-api-name="Account" 
	record-id={recordId}
    onsubmit={handleSubmit}
    onsuccess={handleSuccess}
    onerror={handleError}>
	</lightning-record-edit-form>

</template>
lightning-record-edit-form tag used in LWC
import { LightningElement } from 'lwc'

export default HelloWorld extends LightningElement{
	handleSubmit(){
    	console.log('IN SUBMIT');
    }
    handleSuccess(){
    	console.log('IN SUCCESS');
    }
    handleError(){
	    console.log('IN ERROR');
    }
}
Controller of the LWC implementing helper functions

Hope this is helpful!