Using lightning-record-form in LWC
Let's look at how to use lightning-record-form tag to interact with a single record and perform DML operation.
This tag is a little bit advanced than the other two tags lightning-record-edit-form
and lightning-record-view-form
.
In the above mentioned two tags, we need to specify the fields that we need to work with.
Here is a snippet explaining that!
If you notice it we are explicitly mentioning the fields one after the other. When the ask is to do something like field high-lighting or have more granular control over the fields then we will be using the above-mentioned tags.
If the object has a bunch of fields (say 100+) and if we are not interested in manually displaying them one after the other then we will be going ahead with the tag lightning-record-form
Let's look at a snippet using the tag!
We are sending dynamic values to record-id
. As of now am hardcoding the value for object-api-name
but we can make that dynamic too.
We can also use an attribute called layout-type
to which we can provide the value as Full
or Compact
.
If the value is Full
then all the fields from the page layout will be fetched and displayed automatically without specifying any field name separately.
Likewise, if the value is Compact
then all the fields from the compact page layout will be fetched and displayed.
Also, there is an attribute called mode to which we can provide 3 values which are namely readonly
edit
and view
.
- readonly - if the mode is readonly record will be fetched in readonly format.
- edit - in this mode, the record is fetched in edit mode. Edit functionality is fully functional. Once the record is created or updated the record gets to view mode.
- view - In this mode, the record can be viewed but edit icons will be given to edit the record.
If we don't provide record-id then the same tag can be used to create a record. If the record-id is provided then we can update the record.
Easy isn't it?
Wait! There is a catch.
What if you are not interested in displaying all the fields of the page layout and what if you are interested in displaying (let's say) only 10 fields from the list of all fields.
In that case, we can use a new attribute called fields
. To this attribute, we need to pass an array of fields that we are interested in fetching and displaying.
Let's look at the controller of the Web Component(check the comments).
One of the major advantages is we don't have to write any logic to save or update the record. We don't even have to write the code to create a button.
Hope this was helpful!