Reusable custom lookup field in Lightning Web Component

CUSTOM LOOKUP FIELD IN LIGHTNING WEB COMPONENT requires a lot of code, but what if i tells you that you can do this with few lines of code? Yes, we can make use of Lightning Data Service to achieve it.

Lightning Data Service powers the wire adapters and functions in the lightning/ui*Api modules. It also powers the lightning-record-edit-formlightning-record-form, and lightning-record-view-form components.

We are going to use the lightning-record-edit-form component to create a simple form with a lookup field.

Let’s create a reusable Lightning Web Component with name customLookup. Lightning Web Component has three files when you create it. We have:-

  • customLookup.html
  • customLookup.js
  • customLookup.js-meta.xml
CUSTOM LOOKUP FIELD IN LIGHTNING WEB COMPONENT

Public Properties of customLookup Component

  • childObjectApiName – The API Name of the Object on which Lookup field exist
  • targetFieldApiName – The API Name of the Lookup field
  • fieldLabel – The label of the custom lookup field
  • disabled – It decide weather the lookup field appears as disabled or not
  • value – Use this property to populate the default lookup field value
  • required – It decide the selection is required or not

customLookup.html

The html has lightning-record-edit-form component which just used to load a lookup field when object API name and field API name of object is passed. The lightning-input-field component display and edit the value of a record field of a Salesforce object. We have defined a onchange handler on the lightning-input-field to get the value selected by user in the lookup field.

<template>
    <lightning-record-edit-form object-api-name={childObjectApiName}>
        <label for="fieldid">{fieldLabel}</label>
        <lightning-input-field id="fieldid" required={required} variant="label-hidden" field-name={targetFieldApiName}
            value={value} onchange={handleChange} disabled={disabled}>
        </lightning-input-field>
    </lightning-record-edit-form>
</template>

We did not used the submit button of the lightning-record-edit-form because we just want to create a form that can be used in other Lightning Web Components or Aura Components.

customLookup.js

The JavaScript file of the Custom Lookup Lightning Web Component has two methods and few properties. handleChange method fires the custom event to send id of the selected record in lookup field. Also, If you want to validate the lookup field weather user has selected the record or not, You can make use of isValid method which is annotated with @api decorator which makes it public method and can be called from the other lightning components where this component is being called.

import { LightningElement, api } from 'lwc';

export default class CustomLookup extends LightningElement {
    @api childObjectApiName = 'Contact'; //Contact is the default value
    @api targetFieldApiName = 'AccountId'; //AccountId is the default value
    @api fieldLabel = 'Your field label here';
    @api disabled = false;
    @api value;
    @api required = false;

    handleChange(event) {
        // Creates the event
        const selectedEvent = new CustomEvent('valueselected', {
            detail: event.detail.value
        });
        //dispatching the custom event
        this.dispatchEvent(selectedEvent);
    }

    @api isValid() {
        if (this.required) {
            this.template.querySelector('lightning-input-field').reportValidity();
        }
    }
}

customLookup.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>false</isExposed>
</LightningComponentBundle>

Demo – Lets see how to use Custom Lookup Field in another Lightning Web Component

We are going to create another Lightning Web Component with name hostLookupInLwc. It also has three files:-

  • hostLookupInLwc.html
  • hostLookupInLwc.js
  • hostLookupInLwc.js-meta.xml

We are going to call the custom Lookup component in hostLookupInLwc and pass the public properties value.

hostLookupInLwc.html

When you are calling c-custom-lookup in your component, You must handle the event name onvalueselected which gives you the id of the record in Lookup field. We have handled the event with handleValueSelcted method in JavaScript file. We are going to look for Account records using Lookup field.

<template>
    <div class="slds-card">
        <c-custom-lookup field-label="Select Account Record" child-object-api-name='Opportunity'
            target-field-api-name='AccountId' required onvalueselected={handleValueSelcted}></c-custom-lookup>
        The selected record Id is:- {selectedRecordId}
    </div>
</template>

hostLookupInLwc.js

To fetch the value of the event dispatched, you event.detail.

import { LightningElement } from 'lwc';

export default class HostLookupInLwc extends LightningElement {
    selectedRecordId; //store the record id of the selected 
    handleValueSelcted(event) {
        this.selectedRecordId = event.detail;
    }
}

To validate the lookup field when you pass the required attribute as true by firing a method defined in JavaScript file:-

validateLookupField() {
        this.template.querySelector('c-custom-lookup').isValid();
}

hostLookupInLwc.js-meta.xml

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

Have you set up your developer environment for Lightning Web Component? Read this blog to set it up:- https://salesforcediaries.com/2019/02/21/setup-your-developer-environment-for-lightning-web-comp/

10 comments

  1. The lookup component works fine. But if I use multiple c-look-up components on a same page, the custom events will be handled by different handler, is there any way to prevent it? Thanks.

  2. Hi Sanket,
    Great Blog and so informative!!
    After selecting the account with the lookup I want create event(calendar)how to implement that please help me with it.

    Thanks
    Reena

  3. Hi Sanket,

    I am new to Lightning web Components..
    From the above with custom lookup I want to create or see the todays/future Events for the selected account. How can
    I achieve this continuation to your code.

    Many thanks in advance
    Prema

  4. how can we achieve a related contacts for selected account by reusing this component same for the contacts

Leave a Reply