SalesforceBlue

Feel the rhythm of Salesforce

LWC

Using lightning-record-form Component

Using this component to create record forms is easier than building forms manually with lightning-record-edit-form or lightning-record-view-form. The lightning-record-form component provides these helpful features:

  • Switches between view and edit modes automatically when the user begins editing a field in a view form
  • Provides Cancel and Save buttons automatically in edit forms
  • Uses the object’s default record layout with support for multiple columns
  • Loads all fields in the object’s compact or full layout, or only the fields you specify

lightning-record-form implements Lightning Data Service and doesn’t require additional Apex controllers to create or edit record data. It also takes care of field-level security and sharing for you, so users see only the data that they have access to.

Load A Record Using lightning-record-form:

The simplest way to display a record is to use the lightning-record-form. Let’s understand this with the below example:

Create a component(LWC) with the name as lwcLightningRecordForm and add the following code:

<template>
    <lightning-card title="Lightnig Record Form">
        <lightning-record-form
        record-id={recordId}
        object-api-name={objectApiName}
        fields={fields}
        mode="readonly">
        </lightning-record-form> 
    </lightning-card>
</template> 

Here mode Specifies the interaction and display style for the form. Possible values: view, edit, readonly. If a record ID is not provided, the default mode is edit, which displays a form to create new records.

If a record ID is provided, the default mode is view, which displays field values with edit icons on updateable fields.

import { LightningElement, api } from 'lwc';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import PHONE_FIELD from '@salesforce/schema/Account.Phone';
import ANNUALREVENUE_FIELD from '@salesforce/schema/Account.AnnualRevenue';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';

export default class LwcRecordViewForm extends LightningElement {
    @api recordId;
    objectApiName = ACCOUNT_OBJECT;
    fields = [NAME_FIELD, PHONE_FIELD, ANNUALREVENUE_FIELD];
}

On Line 2-5 we are importing the references of fields and object.

At Line 8 we have created a public property recordId which will inherit the record Id if placed on the account’s record page.

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
  <apiVersion>52.0</apiVersion>
  <isExposed>true</isExposed>
  <targets>
    <target>lightning__AppPage</target>
    <target>lightning__RecordPage</target>
    <target>lightning__HomePage</target>
  </targets>
</LightningComponentBundle>

Please add this component to the account record page. You will get an output like the below:


Edit A Record Using lightning-record-form:

Let’s update the lwcRecordForm component created above to edit a record.

Here we have added the mode=”edit” along with onsubmit and onsuccess handler.

<template>
    <lightning-card title="Quick Edit">
        <lightning-record-form
        record-id={recordId}
        object-api-name={objectApiName}
        fields={fields}
        mode="edit"
        onsubmit={handleSubmit}
        onsuccess={handleSuccess}>
        </lightning-record-form> 
    </lightning-card>
</template>
import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

import NAME_FIELD from '@salesforce/schema/Account.Name';
import PHONE_FIELD from '@salesforce/schema/Account.Phone';
import ANNUALREVENUE_FIELD from '@salesforce/schema/Account.AnnualRevenue';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';


export default class LwcRecordForm extends LightningElement {
    @api recordId;
    objectApiName = ACCOUNT_OBJECT;
    fields = [NAME_FIELD, PHONE_FIELD, ANNUALREVENUE_FIELD];

    handleSubmit(event) {      
        // Here we are overriding AnnualRevenue just for demo purpose. 
        // On the project you can do a field validation or appending/overriding any information to a field
        event.preventDefault(); // stop the form from submitting
        const fields = event.detail.fields;
        fields.AnnualRevenue = '2000000'; // modify a field
        this.template.querySelector('lightning-record-form').submit(fields);
    }

    handleSuccess(event) {
        const evt = new ShowToastEvent({
            title: 'Account Updated',
            message: 'Record ID: ' + event.detail.id,
            variant: 'success',

        });
        
        this.dispatchEvent(evt);
    }

}

Create A Record Using lightning-record-form:

For this example we would be creating contact records from account detail page. Here we have not added the record-id as done in above cases.

<template>
    <lightning-card title="Quick Contact Create">
        <lightning-record-form
        object-api-name={objectApiName}
        fields={fields}
        onsubmit={handleSubmit}
        onsuccess={handleSuccess}>
        </lightning-record-form> 
    </lightning-card>
</template>
import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

import FIRST_NAME_FIELD from '@salesforce/schema/Contact.FirstName';
import LAST_NAME_FIELD from '@salesforce/schema/Contact.LastName';
import ACCOUNT_ID_FIELD from '@salesforce/schema/Contact.AccountId';
import CONTACT_OBJECT from '@salesforce/schema/Contact';



export default class LwcRecordForm extends LightningElement {
    @api recordId;
    objectApiName = CONTACT_OBJECT;
    fields = [FIRST_NAME_FIELD, LAST_NAME_FIELD];

    handleSubmit(event) {
        
        event.preventDefault(); // stop the form from submitting
        const fields = event.detail.fields;
        fields.ACCOUNT_ID_FIELD = this.recordId;
        this.template.querySelector('lightning-record-form').submit(fields);
    }

    handleSuccess(event) {
        const evt = new ShowToastEvent({
            title: 'Contact Created',
            message: 'Record ID: ' + event.detail.id,
            variant: 'success',

        });
        
        this.dispatchEvent(evt);
    }

}

Preview the above component in the account record page. You will get an output like below:


Here is the complete reference of lightning-record-form. Please click on the link to check out the official docs for lightning-record-form.

Thank you for visiting SalesforceBlue.com
If you have any queries feel free to write down a comment below 🙂


Leave a Reply

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