Icon for the Lightning Components topic

How to create a reusable Lookup Lightning Component [Aura]

In this tutorial, I will show you how to create a reusable Lookup Lightning Component using Lightning Aura 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:recordEditForm” to access the fields of the Contact Object.
  • Inside “lightning:recordEditForm” we use a “lightning:inputField” 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.

lookupComponent.cmp

<aura:component controller="SfWiki_Handler" access="global">

    <!-- Attributes -->
    <aura:attribute name="name" type="String" default=""/>
    <aura:attribute name="variantLabel" type="String" default="label-hidden"/>
    <aura:attribute name="fieldLabel" type="String" default=""/>
    <aura:attribute name="childObjectApiName" type="String" default=""/>
    <aura:attribute name="targetFieldApiName" type="String" default=""/>
    <aura:attribute name="value" type="String" default=""/>
    <aura:attribute name="required" type="Boolean" default="false"/>
    <aura:attribute name="addToRecent" type="Boolean" default="false"/>

    <!-- Register Event -->
    <aura:registerEvent name="lookupEvent" type="c:componentEvent"/>

    <lightning:recordEditForm objectApiName="{!v.childObjectApiName}">
        <div class="slds-form-element">
            <aura:if isTrue="{!v.required}">
                <label class="slds-float_left"><abbr title="required" class="slds-required">*</abbr>{!v.fieldLabel}</label>
                <aura:set attribute="else">
                    <label class="slds-float_left">{!v.fieldLabel}</label>
                </aura:set>
            </aura:if>

            <div class="slds-form-element__control">
                <lightning:inputField
                        aura:id="lookupField"
                        variant="{!v.variantLabel}"
                        fieldName="{!v.targetFieldApiName}"
                        value="{!v.value}"
                        required="{!v.required}"
                        onchange="{!c.handleChange}"
                />
            </div>
        </div>
    </lightning:recordEditForm>

</aura:component>

lookupComponentController.js

({
    handleChange: function(component, event, helper) {
        let selectedValue = component.get("v.value");

        //Send the recordId to "Example Component"
        let componentEvent = component.getEvent("lookupEvent");
        componentEvent.setParams({
            "recordId" : selectedValue[0]
        });
        componentEvent.fire();

        //Add to recent list
        if(component.get("v.addToRecent") === true) {
            if(selectedValue !== undefined) {
                if (selectedValue.length > 0 && selectedValue[0].length > 0) {
                    let action = component.get("c.setObjectToRecentItems");
                    action.setParams({
                        "recordId": selectedValue[0]
                    });
                    $A.enqueueAction(action);
                }
            }
        }

        //ReportValidity
        let lookupField = component.find("lookupField");
        lookupField.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

First of all you need in Lightning Aura Components a Component Event. Create one and name it “componentEvent”. Then copy the Code-Snippet below and paste it there.

componentEvent.evt

<aura:event type="COMPONENT">
    <aura:attribute name="recordId" type="String"/>
</aura:event>

exampleComponent.cmp

<aura:component implements="flexipage:availableForAllPageTypes" access="global">

    <!-- Load CSS from Static Resources -->
    <ltng:require styles="{!$Resource.noHeader}"/>

    <!-- Attributes -->
    <aura:attribute name="accountId" type="Id" default=""/>

    <!-- Event Handler -->
    <aura:handler name="lookupEvent" event="c:componentEvent" action="{!c.handleComponentEvent}"/>

    <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 iconName="standard:custom_notification" size="small"/>
            </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:lookupComponent
                            name="accountLookup"
                            fieldLabel="Account"
                            childObjectApiName="Contact"
                            targetFieldApiName="AccountId"
                            value="{!v.accountId}"
                            required="true"
                            addToRecent="true"
                    />
                </div>
                <p>Id of the selected Account: <span style="font-weight: bold">{!v.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>

</aura:component>

exampleComponentController.js

({
    handleComponentEvent : function(component, event, helper) {
        component.set("v.accountId", event.getParam("recordId"));
    }
});

That’s it!

I hope you have enjoyed learning “How to creae a reusable Lookup Lightning Component [Aura]”. 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 Web Components, here’s the link to it: How to create a reusable Lookup Lightning Component [LWC].

How to create a reusable field search Lightning Component using Lightning Aura Components

How to create a reusable field search Lightning Component [Aura]

In this tutorial, I will show you how to create a reusable field search Lightning Component in Lightning Aura Components.

How to create a reusable field search Lightning Component using Lightning Web Components

How to create a reusable field search Lightning Component [LWC]

In this tutorial, I will show you how to create a reusable field search Lightning Component in Lightning Web Components.

How to create a reusable Lookup Lightning Component

How to create a reusable Lookup Lightning Component [Aura]

In this tutorial, I will show you how to create a reusable Lookup Lightning Component in Lightning Aura Components.

How to create a reusable Lookup Lightning Component

How to create a reusable Lookup Lightning Component [LWC]

In this tutorial, I will show you how to create a reusable Lookup Lightning Component in Lightning Web Components.

How to remove Lightning App Page Header

How to remove Lightning App Page Header [Aura]

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

Leave a comment!

0 0 votes
Article Rating
guest
0 Comments
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.