Concepts or coding lessons of Salesforce that you can implement easily

Create Custom Lookup in LWC in Simple way

 In this blog we are going to see how to create Custom lookup in LWC.


1. Create CustomLookupControllerLWC apex class and copy paste below code

public with sharing class CustomLookupControllerLWC {
    @AuraEnabled(cacheable=true)
    public static List<SObject> searchRecords(String objName,
                String fieldApiName, String searchVal){
        try {
            String key = '%' + searchVal + '%';
            String query = 'SELECT Id,'+ fieldApiName + ' FROM '+
                objName +' WHERE '+fieldApiName+' LIKE : key';
            List<SObject> lstObject = Database.query(query);
            return lstObject;
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }
}

2. Create recordList LWC component and copy paste below code into html file. 

<template>
    <div class="slds-grid slds-wrap slds-dropdown_length-with-icon-7
        slsd-dropdown_fluid slds-var-p-left_small">
        <div class="slds-col slds-size_4-of-4">
            <ul class="slds-listbox slds-listbox_vertical" role="presentation">
                <li class="slds-listbox__item">
                    <div class="slds-media slds-listbox__option
                        slds-listbox__option_entity slds-listbox__option_has-meta"
                        role="option" onclick={handleSelect}>
                        <span class="slds-media__figure slds-listbox__option-icon">
                            <lightning-icon
                              icon-name={iconname}
                              size="small"
                            ></lightning-icon>
                        </span>
                        <span class="slds-media__body"
                            style="padding-top: 9px;font-weight:600">
                            {record.Name}
                        </span>
                    </div>
                </li>
            </ul>
        </div>
    </div>
</template>

Copy paste below code into recordList .js file

import { LightningElement, api } from 'lwc';

export default class RecordList extends LightningElement {
    @api record;
    @api iconname;

    handleSelect(){
        console.log('this.record.id '+this.record.Id);
        const selectedEvent = new CustomEvent(
            'select',
            {
                detail : this.record.Id
            }
        );
        this.dispatchEvent(selectedEvent);
    }
}

3. Create searchCmp LWC component and copy paste below code into html file

<template>
    <lightning-input
      type="text"
      variant="label-hidden"
      onchange={handleChange}
      value={searchValue}
    ></lightning-input>
</template>

Copy paste below code into searchCmp .js file

import { LightningElement, track } from 'lwc';

export default class SearchCmp extends LightningElement {
    @track searchValue;

    handleChange(event){
        const val = event.target.value;
        this.searchValue = val;

        const searchEvt = new CustomEvent(
            'searchevent',
            {
                detail : this.searchValue
            }
        );
        console.log('before dispatchEvent');
        this.dispatchEvent(searchEvt);
    }

}

4. Create customLookup LWC component and copy paste below code into html file

<template>
    <template if:false={selectedRec}>
        <c-search-cmp onsearchevent={handleSearchHandle}></c-search-cmp>
    </template>

    <template if:false={selectedRec}>
        <template if:true={records}>
            <template for:each={records} for:item="rec">            
                <c-record-list key={rec.Id} record={rec} iconname={iconname}
                onselect={handleSelect}></c-record-list>
            </template>
        </template>
    </template>

    <template if:true={selectedRec}>
        {selectedRec.Name}
    </template>

</template>

Copy paste below code into customLookup.js file

import { LightningElement, api, track } from 'lwc';
import searchRecords from '@salesforce/apex/CustomLookupControllerLWC.searchRecords'
export default class CustomLookup extends LightningElement {

    @api objectApiName ;
    @api fieldApiName;
    @api iconname;
    @track records;
    @track errors;
    @track selectedRec;

    handleSearchHandle(event){
        console.log('in handle event');
        const searchValue = event.detail;

        // Call apex method and create below Promise
        searchRecords({
            objName : this.objectApiName,
            fieldApiName : this.fieldApiName,
            searchVal : searchValue
        })
        .then(result => {
            console.log('Records are ', result);
            this.records = result;
            this.errors = undefined;
        })
        .catch(error =>{
            this.records = undefined;
            this.errors = error;
        })
    }

    handleSelect(event){
        console.log('in handleSelect ');
        const accId = event.detail;
        console.log('accId '+accId);
        const selectedRecord = this.records.find(
            rec => rec.Id === accId
        );
        /*
            above selectedRecord act like below
            this.records.find(account => account.Id === accountId);
            OR
            for(account acc : records){
                if(account.Id === accountId){
                    return acc;
                }
            }
        */
        console.log('Selected record ', selectedRecord);
        this.selectedRec = selectedRecord;
    }
}

Subscribe blog for More updates !!! 


Read More: WhatsApp on Salesforce Integration in 5 Steps
                    Which Salesforce API Do I Use in Integration?
                    When To Use Salesforce REST API  
                   When To Use Salesforce SOAP API 
                   When To Use Salesforce Bulk API 


Latest Salesforce Interview Questions and Answers: