Icon for the Lightning Components topic

How to create a reusable Lookup Lightning Component [LWC]

In this tutorial, I will show you how to create a reusable Lookup Lightning Component using Lightning Web Components. In the GIF below you can see the final result.

How to create a reusable Lookup Lightning Component

A brief summary of how the Lookup Lightning Component works:

  • We use “lightning-record-edit-form” to access the fields of the Contact Object.
  • Inside “lightning-record-edit-form” we use a “lightning-input-field” to access the “AccountId” field of the Contact Object.
  • So we have a 1:1 representation of the Account Lookup field that is on the Contact Object.
  • When an Account is selected, the Id of the Account is sent to the Parent Component via a Component Event and packed into the Recent List.

lwcLookupComponent.html

<template>
    <lightning-record-edit-form object-api-name={childObjectApiName}>
        <div class="slds-form-element">
            <label class="slds-float_left"><abbr if:true={required} title="required" class="slds-required">*</abbr>{fieldLabel}</label>
            <div class="slds-form-element__control">
                <lightning-input-field
                        variant={variant}
                        field-name={targetFieldApiName}
                        value={value}
                        required={required}
                        onchange={handleChange}
                >
                </lightning-input-field>
            </div>
        </div>
    </lightning-record-edit-form>
</template>

lwcLookupComponent.js

import { LightningElement, api } from 'lwc';
import addToRecentItems from '@salesforce/apex/SfWiki_Handler.setObjectToRecentItems';

export default class LwcLookupComponent extends LightningElement {

    @api name;
    @api variant = "label-hidden";
    @api fieldLabel;
    @api childObjectApiName;
    @api targetFieldApiName;
    @api value;
    @api required = false;
    @api addToRecent = false;

    handleChange(event) {
        let selectedEvent = new CustomEvent('valueselected', {detail: event.detail.value[0]});
        this.dispatchEvent(selectedEvent);

        if (this.addToRecent) {
            if (event.detail.value.length > 0 && event.detail.value[0].length > 0) {
                addToRecentItems({
                    recordId: event.detail.value[0]
                })
                    .catch(error => {
                        console.log(error);
                    });
            }
        }
    }

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

}

SfWiki_Handler.cls

public without sharing class SfWiki_Handler {

    @AuraEnabled
    public static void setObjectToRecentItems(Id recordId) {
        if (!String.isBlank(recordId)) {
            Schema.SObjectType sObjectType = recordId.getSobjectType();
            String queryString = String.format('SELECT Id, Name FROM {0} WHERE Id =: recordId FOR VIEW', new List<Object>{sObjectType});
            Database.query(queryString);
        }
    }

}

Example how to use

lwcExampleComponent.html

<template>

    <div class="slds-card" style="font-family: 'Open Sans', sans-serif">

        <!-- Header -->
        <header class="slds-card__header slds-media slds-media_center">
            <div class="slds-media__figure">
                <lightning-icon icon-name="standard:custom_notification" size="small"></lightning-icon>
            </div>
            <div class="slds-media__body slds-card__header-title slds-text-title_bold" style="font-size: 14px">
                Example Component
            </div>
        </header>

        <!-- Body -->
        <div class="slds-p-around_small">
            <div class="slds-text-align_center slds-container_center" style="font-size: 15px;">
                <div class="slds-size_2-of-3 slds-align_absolute-center slds-p-bottom_small">
                    <c-lwc-lookup-component
                            name="accountLookup"
                            field-label="Account"
                            child-object-api-name="Contact"
                            target-field-api-name="AccountId"
                            value={accountId}
                            required="false"
                            add-to-recent="true"
                            onvalueselected={handleSelectedLookup}
                    >
                    </c-lwc-lookup-component>
                </div>
                <p>Id of the selected Account: <span style="font-weight: bold">{accountId}</span></p>
                <p class="slds-p-top_small">Hope you like this tutorial</p>
                <p style="font-weight: bold; color: red">Sf <span style="font-weight: bold; color: black">Wiki</span></p>
            </div>
        </div>

    </div>

</template>

lwcExampleComponent.js

import {LightningElement} from 'lwc';

export default class LwcExampleComponent extends LightningElement {

    accountId;

    handleSelectedLookup(event) {
        this.accountId = event.detail;
    }

}

That’s it!

I hope you have enjoyed learning “How to create a reusable Lookup Lightning Component [LWC]”. Please share your thoughts in the comments below. If you find value in this type of post, please subscribe because we have tons of tutorials in progress to be posted!

If you prefer to see the result with Lightning Aura Components, here’s the link to it: How to create a reusable Lookup Lightning Component [Aura].

How to assign Profile User to a Permission Set in Apex

How to assign Profile User to a Permission Set in Apex?It often happens that one of my customers wants to have a new permission set created and at the same time wants the users of one or more profiles assigned to this new permission set. This is easily done...

How to create a reusable field search Lightning Web Component

How to create a reusable field search Lightning Web ComponentIn this tutorial, I will show you how to create a reusable field search Lightning Web Component. In the GIF below you can see the final result.   A brief summary of how the field search Lightning...

How to remove Lightning App Page Header [LWC]

In this tutorial, I will show you how to remove Lightning App Page Header in Lightning Web Components.

How to add or remove rows dynamically [LWC]

In this tutorial, I will show you how to add or remove rows dynamically in Lightning Web Components.

How to navigate through Lightning Components [LWC]

In this tutorial, I will show you how to navigate through Lightning Components in Lightning Web Components.

Leave a comment!

0 0 votes
Article Rating
Subscribe
Notify of
guest
5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Hamid Abassi

Hamid Abassi

SfWiki Founder

I am a Salesforce Developer from Hamburg who wants to help the Salesforce Community around the world with my tutorials. Feel free to explore my website and hopefully learn something new.

devHamid