Salesforce

Working of force:recordData

Lightning Web Components

force:recordData component is part of lightning data service. At the simplest level, you can think of Lightning Data Service as the lightning components version of the visualforce standard controller. By using, Lightning Data Service we can eliminate the need for writing server side Apex code.

We can use force:recordData to load, create, edit or delete a particular record without having to write Apex code.

Loading a Record:

To load a record we need to add force:recordData tag in our component and specify the Id of the record to load, a list of fields and the attribute to which the loaded record is to be assigned.

Fields to specify to load record:
1. Id of the record to load
2. Component attribute to assign the loaded record
3. A list of fields to load

You can explicitly specify a list of fields to load with the fields attribute. For example:
fields=”Name, BillingCity, BillingState”. Alternatively, We can specify a layout using the layoutType attribute. All fields in that layout will be loaded. Valid values for the layoutType are FULL and COMPACT.

Note: This component sets the record data in the attribute. If you want to display the different fields you will need to do that explictly.

Consider the following code:
Output:

Save a Record:

To save a record using force:recordData call saveRecord on the force:recordData component, and pass a callback function to be invoked after the save operation completes.

Save operation  used in two cases:

  1. changes to existing record (Update record)
  2. create a new record

To save changes to an existing record, load the record in EDIT mode and call saveRecord on the force:recordData component.

Consider the following component:
Output:

Create a Record:

To create a record using force:recordData declare the force:recordData tag without assigning a recordId. To achieve this we need to create an empty record from a record template. The empty record is saved to the targetRecord attribute. After that we need to invoke the saveRecord of the component.

Consider the following code:
Output:

Delete a record:

To delete a record, call deleteRecord on the force:recordData component. And pass in a calback function to be invoked after the delete operation completes. To delete a record you only need to pass the record id of the record.

Consider the following code:
Output:

Try demo: