Apex Wire Method to Function

Now, we will see how we can get the Salesforce Record details using Apex Class – Wiring to Function mechanism. This mechanism is needed if you want to pre-process the data before going to the Lightning App.

To do this exercise, we will try to show a Contact Record in Lightning App.

Step 1: We have created an Apex Class named “LWC_ContactController” by which we will send the Contact record to Lightning Web Component. We can take the same Apex Class with the same method for this exercise as mentioned in the session “Apex Wire Method to Property”.

LWC_ContactController.cls

1
2
3
4
5
6
7
public with sharing class LWC_ContactController{
       
       @AuraEnabled(cacheable = true)
       public static List<Contact> getContactList(){
           return [SELECT Id, Name, Email FROM Contact LIMIT 1];
       }
}

getContactList() method of the Apex Class “LWC_ContactController” returns the Contact Record.

Step 2: After that, we have built a LWC named “showContactsWMF“. As per previous examples, we need to update the “showContactsWMF.js-meta.xml” file to set the visibility in Lightning App Builder.

showContactsWMF.js-meta.xml

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="showContactsWMF">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Step 3: Need to write the respective HTML file.

showContactsWMF.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<template>
        <lightning-card title="Apex Wire Method To Function">            
            <lightning-layout>
              <lightning-layout-item flexibility="auto" padding="around-small">
                   <template if:true={contacts}>                        
                        <template for:each={contacts} for:item="contact">                        
                            <p key={contact.Id}>                              
                                {contact.Name}
                                <lightning-formatted-email value={contact.Email} class="slds-m-left_medium"></lightning-formatted-email>
                            </p>
                        </template>
                    </template>
                    <template if:true={error}>
                        {error}>
                    </template>
              </lightning-layout-item>
            </lightning-layout>
          </lightning-card>
</template>

Step 4: Now, we need to work on the JS file.

showContactsWMF.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { LightningElement, wire, track } from 'lwc';
import getContactList from '@salesforce/apex/LWC_ContactController.getContactList';

export default class ShowContactsWMF extends LightningElement {

    @track contacts;
    @track error;

    @wire(getContactList)
        wiredContacts({data, error}){
            if(data){
                this.contacts = data;
                this.error = undefined;
            }
            else if (error) {
                this.error = error;
                this.contacts = undefined;
            }
        }
}

As per the wire method writing rules, first we have imported “getContactList” from the Apex Class, “LWC_ContactController“. Then, the function named wiredContacts is wired to getContactList in this way
@wire(getContactList)
wiredContacts({data, error}){ }

We have defined two private reactive properties such as contacts and error. We have set these two properties into the wired function named wiredContacts. Hence, we will get the Contact record details using only {contacts} instead of {contact.data} applied for wire method to property mechanism in HTML file. And obviously, we will get the errors using {error} in HTML file.

We have used wire mechanism so, the cacheable of the respective method, getContactList() of the Apex Class “LWC_ContactController” should be true.

Step 5: At last, need to add this LWC into Lightning App/Home or Record Page.

Result

9,766 total views, 6 views today

Posted in Lightning Web Component | Leave a comment

Apex Wire Method to Property with Parameters

Now, we will see how we can get the Salesforce Record details based on some parameters using Apex Class – Wiring to Property with Parameters mechanism.

To do this exercise, we will try to search Contact Records based on Account Name in Lightning App.

Step 1: We have created an Apex Class named “LWC_ContactController” by which we will send the Contact record to Lightning Web Component based on Account Name. We can update the same Apex Class to consider the specific business.

LWC_ContactController.cls

public with sharing class LWC_ContactController{
       
      @AuraEnabled(cacheable = true)
       public static List<Contact> searchContactList(String accountName){
           if (String.isBlank(accountName)) {
                return new List<Contact>();
            }
           
            String key = '%' + accountName + '%';            
            return [SELECT Id, Name, Email FROM Contact WHERE Account.Name LIKE : key];
       }
}

searchContactList() method of the Apex Class “LWC_ContactController” returns the Contact Records based on Account Name.

Step 2: After that, we have built a LWC named “showContactsWMPP“. As per previous examples, we need to update the “showContactsWMPP.js-meta.xml” file to set the visibility in Lightning App Builder.

showContactsWMPP.js-meta.xml

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

Step 3: Need to write the respective HTML file.

showContactsWMPP.html

<template>
        <lightning-card title="Apex Wire Method With Property Parameters">            
            <lightning-layout> 
              <lightning-layout-item flexibility="auto" padding="around-small">
                   <lightning-input label="Enter Account Name" type="search"  onchange={searchContact} value={searchKey}></lightning-input>
                    <template if:true={contacts.data}> 
                        <br/>                       
                        <template for:each={contacts.data} for:item="contact">                        
                            <p key={contact.Id}>                               
                                {contact.Name}
                            </p> 
                        </template>
                    </template>
                    <template if:true={contacts.error}>
                        {contacts.error}>
                    </template>
              </lightning-layout-item>
            </lightning-layout>
          </lightning-card>
</template>

Step 4: Now, we need to work on the JS file.

showContactsWMPP.js

import { LightningElement, track, wire } from 'lwc';
import searchContactList from '@salesforce/apex/LWC_ContactController.searchContactList';

const DELAY = 300;

export default class ShowContactsWMFP extends LightningElement {
    @track searchKey = '';
    
    @wire(searchContactList, {accountName:'$searchKey'}) contacts;

    searchContact(event){
        window.clearTimeout(this.delayTimeout);
        const searchKey = event.target.value;
        // eslint-disable-next-line @lwc/lwc/no-async-operation
        this.delayTimeout = setTimeout(() => {
            this.searchKey = searchKey;
        }, DELAY);
    }
}

As per the wire method writing rules, first we have imported “searchContactList” from the Apex Class, “LWC_ContactController“. Then, property contacts is wired to searchContactList with parameters in this way

@wire(searchContactList, {accountName:’$searchKey’}) contacts;  – where “searchkey” is the user input defines the Account Name. During passing of the parameters, we need to put ‘$’ sign before the property.

Remember, contacts is the property of wiring, that means we can get the data of contact using {contacts.data} & also we can get the error using {contacts.error} in html file and contacts is also the reactive property.

We have used wire mechanism so, the cacheable of the respective method, searchContactList() of the Apex Class “LWC_ContactController” should be true.

Here, we have defined searchContact(event) function to capture the Search Key as Account Name and set to the original searchKey property and wire adapter will automatically filtered out the Contact records based on Search Key. If the result is same, it will not make the server call.That is the beauty of Lightning web Component.

Step 5: At last, need to add this LWC into Lightning App/Home or Record Page.

Result

18,144 total views, 3 views today

Posted in Lightning Web Component | Leave a comment

Apex Wire Method to Property

Now, we will see how we can get the Salesforce Record details using Apex Class – Wiring to Property mechanism.

To do this exercise, we will try to show a Contact Record in Lightning App.

Step 1: We have created an Apex Class named “LWC_ContactController” by which we will send the Contact record to Lightning Web Component.

LWC_ContactController.cls

public with sharing class LWC_ContactController{
       
       @AuraEnabled(cacheable = true)
       public static List<Contact> getContactList(){
           return [SELECT Id, Name, Email FROM Contact LIMIT 1];
       }
}

getContactList() method of the Apex Class “LWC_ContactController” returns the Contact Record.

Step 2: After that, we have built a LWC named “showContactsWMP“. As per previous examples, we need to update the “showContactsWMP.js-meta.xml” file to set the visibility in Lightning App Builder.

showContactsWMP.js-meta.xml

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

Step 3: Need to write the respective HTML file.

showContactsWMP.html

<template>
    <lightning-card title="Apex Wire Method To Property">        
        <lightning-layout>
          <lightning-layout-item flexibility="auto" padding="around-small">
                <template if:true={contacts.data}>                        
                    <template for:each={contacts.data} for:item="contact">                        
                        <p key={contact.Id}>                               
                            {contact.Name}
                            <lightning-formatted-email value={contact.Email} class="slds-m-left_medium"></lightning-formatted-email>
                        </p>
                    </template>
                </template>
          </lightning-layout-item>
        </lightning-layout>
      </lightning-card>
</template>

Step 4: Now, we need to work on the JS file.

showContactsWMP.js

import { LightningElement, wire } from 'lwc';
import getContactList from '@salesforce/apex/LWC_ContactController.getContactList';

export default class ShowContactsWMP extends LightningElement {
    @wire(getContactList) contacts;
}

As per the wire method writing rules, first we have imported “getContactList” from the Apex Class, “LWC_ContactController“. Then, property contacts is wired to getContactList in this way

@wire(getContactList) contacts;

Remember, contacts is the property of wiring, that means we can get the data of contact using {contacts.data} & also we can get the error using {contacts.error} in html file and contacts is also the reactive property.

We have used wire mechanism so, the cacheable of the respective method, getContactList() of the Apex Class “LWC_ContactController” should be true.

Step 5: At last, need to add this LWC into Lightning App/Home or Record Page.

Result

7,425 total views, 3 views today

Posted in Lightning Components | Leave a comment

Update Record by UI API

Now, we will see how to update a record using UI API.
In this example, we will update the logged-in user record by using uiRecordApi which is a part of the UI API.

So, we have built a LWC named “updateUIRecord“.

Step 1: As per previous examples, we need to update the “updateUIRecord.js-meta.xml” file to set the visibility in Lightning App Builder.

updateUIRecord.js-meta.xml

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

Step 2: Need to write the respective HTML file.

updateUIRecord.html

<template>
    <lightning-card title="Update Record(User) by UIRecordAPI">            
        <lightning-layout> 
            <lightning-layout-item flexibility="auto" padding="around-small">
                <lightning-input label="Company Name" onchange={handleChange}></lightning-input>
                <lightning-input label="Department" onchange={handleChange} class="slds-m-bottom_x-small"></lightning-input>
                <lightning-button label="Update Record" variant="brand" onclick={updateUser}></lightning-button>
            </lightning-layout-item>
        </lightning-layout> 
    </lightning-card>
</template>

Step 3: Now, we need to work on the JS file.

updateUIRecord.js

import { LightningElement } from 'lwc';
import {updateRecord} from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import USER_COMPANY_NAME from '@salesforce/schema/User.CompanyName';
import USER_DEPARTMENT from '@salesforce/schema/User.Department';
import USER_ID from '@salesforce/schema/User.Id';
import CURRENTUSERID from '@salesforce/user/Id';

export default class UpdateUIRecord extends LightningElement {

    companyName;
    department;

    handleChange(event){
        this.fieldValue = event.target.value;        
        if(event.target.label === "Company Name" && this.fieldValue !=='' && this.fieldValue !== undefined)
            this.companyName = this.fieldValue;
        else if(event.target.label === "Department" && this.fieldValue !=='' && this.fieldValue !== undefined)
            this.department = this.fieldValue;              
    }

    updateUser(){

        const fields = {};
        fields[USER_ID.fieldApiName] = CURRENTUSERID;
        fields[USER_COMPANY_NAME.fieldApiName] = this.companyName;
        fields[USER_DEPARTMENT.fieldApiName] = this.department;

        const userRecordInput = { fields };

        updateRecord(userRecordInput)
            .then(()=> {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'User: '+CURRENTUSERID +' has been updated.',
                        variant: 'success',
                    }),
                );
            })
            .catch(error => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error updating record',
                        message: error.body.message,
                        variant: 'error',
                    }),
                );
            });

    }
}

The procedure is same as createRecord from uiRecordAPI. Only, we need to import updateRecord from uiRecordAPI and we don’t need to set the Object API Name because we are sending the User Record Id into the fields which have been used in updateRecord.

Step 4: At last, need to add this LWC into Lightning App/Home or Record Page.

Result

 

 

 

 

 

 

 

 

 

 

In this way, we can use deleteRecord adapter to delete the record.

13,581 total views, 6 views today

Posted in Lightning Web Component | Leave a comment

Create Record by UI API

Now, we will see how to create a record using UI API.
In this example, we will create a Contact record by using uiRecordApi which is a part of the UI API.

So, we have built a LWC named “createUIRecord“.

Step 1: As per previous examples, we need to update the “createUIRecord.js-meta.xml” file to set the visibility in Lightning App Builder.

createUIRecord.js-meta.xml

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

Step 2: Need to write the respective HTML file.

createUIRecord.html

<template>
    <lightning-card title="Create Record(Contact) by UIRecordAPI">            
        <lightning-layout> 
            <lightning-layout-item flexibility="auto" padding="around-small">
                <lightning-input label="First Name" onchange={handleChange}></lightning-input>
                <lightning-input label="Last Name" onchange={handleChange}></lightning-input>
                <lightning-input label="Email" onchange={handleChange} class="slds-m-bottom_x-small"></lightning-input>
                <lightning-button label="Create Record" variant="brand" onclick={createContact}></lightning-button>
            </lightning-layout-item>
        </lightning-layout> 
    </lightning-card>
</template>

Step 3: Now, we need to work on the JS file.

createUIRecord.js

import { LightningElement } from 'lwc';
import {createRecord} from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import CONTACT_OBJECT from '@salesforce/schema/Contact';
import CONTACT_FIRST_NAME from '@salesforce/schema/Contact.FirstName';
import CONTACT_LAST_NAME from '@salesforce/schema/Contact.LastName';
import CONTACT_EMAIL from '@salesforce/schema/Contact.Email';

export default class CreateUIRecord extends LightningElement {

    fieldValue;
    firstName;
    lastName; 
    email;
    contactId;

    handleChange(event){
        this.fieldValue = event.target.value;        
        if(event.target.label === "First Name" && this.fieldValue !=='' && this.fieldValue !== undefined)
            this.firstName = this.fieldValue;
        else if(event.target.label === "Last Name" && this.fieldValue !=='' && this.fieldValue !== undefined)
            this.lastName = this.fieldValue;
        else if(event.target.label === "Email" && this.fieldValue !=='' && this.fieldValue !== undefined)
            this.email = this.fieldValue;        
    }

    createContact(){

        const FIELDS = {};
        FIELDS[CONTACT_FIRST_NAME.fieldApiName] = this.firstName;
        FIELDS[CONTACT_LAST_NAME.fieldApiName] = this.lastName;
        FIELDS[CONTACT_EMAIL.fieldApiName] = this.email;
        
        const contactRecord  = {apiName:CONTACT_OBJECT.objectApiName, fields: FIELDS};
        createRecord(contactRecord)
            .then(contact => {
                this.contactId = contact.id;                
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Contact created. Contact Id: '+this.contactId,
                        variant: 'success',
                    }),
                );
            })
            .catch(error => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,//error.body.output.fieldErrors,
                        variant: 'error',
                    }),
                );
            });
    }
}

Here, we have imported createRecord adapter Id from the adapter module uiRecordApi to create Contact Record. Definitely, as per best practice, we have used Salesforce Schema to define field API Name. platformShowToastEvent adapter module has been used to set the toast messages.

We have created a function named handleChange(event) by which we will set the property based on the field name when user will provide the input in the UI.

Now, we have defined the function named “createContact()” where we have defined “createRecord()” standard function from uiRecordAPI to create the Contact Record. In this “createRecord()” standard function, we have passed the Contact Record details as parameter.

Step 4: At last, need to add this LWC into Lightning App/Home or Record Page.

Result

 

 

 

 

 

 

 

 

 

 

 

 

 

14,793 total views, 9 views today

Posted in Lightning Web Component | Leave a comment

Can we use UI API imperatively in Lightning Web Component?

NOPE. We cannot use UI API imperatively to get the record details in Lightning web Component.

If we will try to use, we will get the following error.

7,665 total views, 9 views today

Posted in Lightning Web Component | Leave a comment

Get record details by UI API

As discussed earlier, Salesforce introduced UI(User Interface) API to build Salesforce UI for mobile and custom web apps by calling this UI API. You don’t need to write Apex Class to fetch data or DML operations, just need to call UI API. This UI API provides the following features as per Salesforce OOB functionality.

  • FLS(Field Level Security)
  • Sharing Settings
  • Use SOQL to get data at backend services
  • Get Object, Theme & Layout Information

Now, we will try to get User details based on logged in User’s Id by UI API.
So, we have created one Lightning Web Component named as “showWireUIStaticUser”.

Step 1: First, we need to update the “showWireUIStaticUser.js-meta.xml” file which is responsible to set the visibility of the component into the Lightning App Builder.

showWireUIStaticUser.js-meta.xml

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

Step 2: Need to update the respective HTML file.

showWireUIStaticUser.html

<template>
    <lightning-card title="Showing Static Record (Wire * UIRecordAPI)">            
        <lightning-layout> 
          <lightning-layout-item flexibility="auto" padding="around-small">
               User 
               <template if:true={userObj.data}> 
                    <div class="slds-m-around_medium">                            
                        <p>{name}</p>
                        <p>{alias}</p>
                        <p><lightning-formatted-email value={email}></lightning-formatted-email></p>
                    </div>
                </template>
                <template if:true={userObj.error}>
                    {userObj.error}>
                </template>
          </lightning-layout-item>
        </lightning-layout> 
    </lightning-card>
</template>

Here, we are trying to show the details such as Name, Alias, Email of the user.

Step 3: Now, we have used UI API by calling uiRecordApi to get the above user details.

showWireUIStaticUser.js

import { LightningElement, wire } from 'lwc';
import CURRENTUSERID from '@salesforce/user/Id'; 
import {getRecord, getFieldValue} from 'lightning/uiRecordApi';

import USER_NAME_FIELD from '@salesforce/schema/User.Name';
import USER_ALIAS_FIELD from '@salesforce/schema/User.Alias';
import USER_EMAIL_FIELD from '@salesforce/schema/User.Email';

const FIELDS= [USER_NAME_FIELD, USER_ALIAS_FIELD, USER_EMAIL_FIELD];

export default class ShowWireUIStaticUser extends LightningElement {

    userId = CURRENTUSERID;

    @wire(getRecord,{recordId: '$userId', fields: FIELDS}) userObj;

    get name(){
        return getFieldValue(this.userObj.data, USER_NAME_FIELD);
    }

    get alias(){
        return getFieldValue(this.userObj.data, USER_ALIAS_FIELD);
    }

    get email(){
        return getFieldValue(this.userObj.data, USER_EMAIL_FIELD);
    }

}

Here, we have imported two adapter Ids or standard functions such as getRecord, getFieldValue from uiRecordApi.
We got the current logged in User’s Id by using ‘@salesforce/user/Id‘ and set this Id to a private property named “userId“.

Now, as per wiring rules, we have used @wire decorator to wire a property named as userObj which is reactive.

@wire(getRecord,{recordId: ‘$userId’, fields: FIELDS}) userObj; – Here we will get the User details by passing the current logged in user’s Id and fields to getRecord adapter. Please notice that we have used $ before the passing property to recordId. It’s applicable for only wire decorator. So, userObj property has user details.

After that, we will use the getter properties to get the value based on a particular field. We can take the example of get Name(). Here, we have used another adapter such as getFieldValue where we need to pass userObj.data and the respective field such as Name to get the details. Actually, getFieldValue finds the information such as Name from the entire User Details(userObj.data).

Step 4: At last, we have to place this component into the Lightning Home/App or Record page.

Result:

 

 

 

 

 

 

 

Q. Why do we have used Salesforce Schema to get fields API Name?

If you see the showWireUIStaticUser.JS file, we have imported field API Name from Salesforce Schema and we have created the array of fields and passed this array to wire service to get the User details. However, we can create the array of fields without using Salesforce Schema just like const fields = [‘Name’, ‘Alias’, ‘Email’];. Here we have just directly put the respective fields’ API Names. Now question is, why do we have used Salesforce Schema?

If we use Salesforce Schema to get the Fields’ API Names, Salesforce considers referential integrity. That means, if the developer wants to delete any field referred in LWC by using Salesforce Schema, System will not allow deleting the field. So, It’s always best practice to use Salesforce Schema to define the Field API Name in LWC.

16,695 total views, 3 views today

Posted in Lightning Web Component | Leave a comment

Wire Service Syntax

Lightning Web Component can get Salesforce Data using a reactive wire service built on Lightning Data Service.

Each value in the immutable stream is the newer version of the value that precedes it.
Wire Service is a reactive service because it supports reactive variables which are prefixed with ‘$’. If this reactive variable changes, the reactive wire service provisions new data instead of making a new server-call.

If the stream has been changed, the component will be re-rendered as per reactive process.

Please see the following image carefully to understand the Wire Service Methodology with Syntax

6,333 total views, 27 views today

Posted in Lightning Web Component | Leave a comment

How to Call Apex Class, get sObject/sObject fields from Lightning Web Component?

7,890 total views, 3 views today

Posted in Lightning Web Component | Leave a comment

Lightning Data Service – Lightning Record Edit Form

Most Powerful Component – lightning-record-edit-form.

Using this component, we can show and edit the record in a customized way. We can override the Save functionality and override the default behavior using this component. We can use lightning-input-field as well as lightning-output-field component into this component. It also doesn’t support all Standard objects like Event, Task.

In this exercise, we will see how to create a Contact record using lightning-record-edit-form.
So, we have built a LWC named “createLREFRecord“.

Step 1: As per previous examples, we need to update the “createLREFRecord.js-meta.xml” file to set the visibility in Lightning App Builder.

createLREFRecord.js-meta.xml

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

Step 2: Need to write the respective HTML file.

createLREFRecord.html

<template>
    <lightning-card title="Create Record(Contact) by Lightning Record Edit Form"  icon-name="standard:contact">
        <div class="slds-m-around_medium">
            <lightning-record-edit-form object-api-name="Contact"
                                        fields={fields}
                                        onsuccess={handleSuccess}>
                <lightning-messages></lightning-messages>

                <template if:true={fields}>
                    <template for:each={fields} for:item="field">
                        <div key={field}>
                            <lightning-input-field field-name={field}></lightning-input-field> 
                        </div>
                    </template>
                </template>
            
                <div class="slds-m-top_medium">
                    <lightning-button variant="brand"
                                    type="submit"
                                    name="save"
                                    label="Save">
                    </lightning-button>
                </div>
            </lightning-record-edit-form>
        </div>
    </lightning-card>
</template>

Here, we have used lightning-record-edit-form component along with lightning-input fields. Only we are taking Contact Last Name to create a Contact record.

Step 3: Now, we need to work on the JS file.

createLREFRecord.js

import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import Contact_LAST_NAME_FIELD from '@salesforce/schema/Contact.LastName';

export default class CreateLREFRecord extends LightningElement {

     fields = [Contact_LAST_NAME_FIELD];

    handleSuccess(event){
        const contactId = event.detail.id;
        if(this.recordId !== null){
            this.dispatchEvent(new ShowToastEvent({
                    title: "SUCCESS! ",
                    message: "Recod "+ contactId +" has been saved.",
                    variant: "success",
                }),
             );
               
        }
    }

}

Here, we have defined fields array which will be set to the property “fields” referred into the lightning-record-edit-form.
We can control the event after successfully saving the record by this component. Here we have invoked handleSuccess(event) function during onsuccess event which is set into the lightning-record-edit-form. handleSuccess(event) function is dedicated to show the toast messages as of now, but you can do other operations after successful saving the record in this function.

Step 4: At last, need to add this LWC into Lightning App/Home or Record Page. Or, you can call this component from another component.

Result

 

 

 

 

 

 

 

 

If you will see the HTML file, we have created a Save button in lightning-record-edit-form. The type of this button is “submit“. Because this button is present into the lightning-record-edit-form, we don’t need to write save function explicitly. But, you can override this behavior. Sometimes, you need to place this button outside of lightning-record-edit-form, at this point of time, you need to invoke the following operation into the respective JS file

handleSubmit(event){
   const fields = event.detail.fields;
   this.template.querySelector('lightning-record-edit-form').submit(fields);
}

We can call the standard “submit” function with defined fields to save the record as well as override default behavior.

We can also call this function during onsubmit of lightning-record-edit-form like onsubmit={handleSubmit}. Basically, lightning-record-edit-form has the following standard event handlers such as “onsubmit”, “onsuccess”, “onerror”.

Only lookup type from this component is supported in Lightning Experience, but this lookup type is not supported in Mobile App. In the Mobile App, lookup type will be represented as input text field as of now.

13,259 total views, 3 views today

Posted in Lightning Web Component | Leave a comment