Hey guys, Today in this post we are going to learn about How to Create a Contact Record With Re-Usable Dynamic Custom Lookup Field in Lightning Web Component – LWC.
Files we used in this post example:-
lwcCreateContactCustomLookup.html | Lightning Web Component HTML | Template HTML file used to write HTML element for build user interface. |
lwcCreateContactCustomLookup.js |
Lightning Web Component JavaScript | It is hold First Name, Last Name, Phone , Email and Submit button click functionality. |
lwcCreateContactCustomLookup.js-meta.xml |
XML Meta File | It is used for where this lightning web component should be exposed. |
lwcAccountCustomLookup.html |
Lightning Web Component HTML | It is Templae HTML file and hold a Account Search Lookup Field. |
lwcAccountCustomLookup.js | Lightning Web Component JavaScript | It is hold Search function and fetch the account name value from database server. |
lwcAccountCustomLookup.js-meta.xml | XML Meta File | It is used for where this lightning web component should be exposed |
lwcApexController.cls | Apex Controller | It is used for Insert a Contact Record with Custom Lookup Field into database sserver |
Live Demo
You can download file directly from github by Click Here.
Other related post that would you like to learn in Salesforce
Step 1:- Create Lightning Web Component : lwcCreateContactCustomLookup.html
SFDX:Lightning Web Component >> New >> lwcCreateContactCustomLookup.html
lwcCreateContactCustomLookup.html [Lightning Web Component HTML]
<template>
<lightning-card title="Create custom lookup on contact object" icon-name="standard:contact">
<div class="slds-p-horizontal_small">
<lightning-input label="First Name" value={firstname} onchange={contactHandleChange} class="slds-m-bottom_x-small slds-p-horizontal_small slds-form-element"></lightning-input>
<lightning-input label="Last Name" value={lastname} onchange={contactHandleChange} class="slds-m-bottom_x-small slds-p-horizontal_small slds-form-element"></lightning-input>
<lightning-input label="Phone" value={phone} onchange={contactHandleChange} class="slds-m-bottom_x-small slds-p-horizontal_small slds-form-element"></lightning-input>
<lightning-input label="Email" value={email} onchange={contactHandleChange} class="slds-m-bottom_x-small slds-p-horizontal_small slds-form-element"></lightning-input>
<c-lwc-account-custom-lookup onselected={myLookupHandle}></c-lwc-account-custom-lookup><br/>
<lightning-button label="Submit" variant="brand" onclick={createLookupContactAction} class="slds-m-bottom_x-small slds-p-horizontal_small slds-form-element"></lightning-button>
</div>
<br/> <br/>
<!--Start RelatedTopics Section-->
<div style="border:1px #ddd solid; padding:10px; background:#eee; margin:40px 0;">
<p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/05/thumbsUpLike.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:16px; font-style:italic; display:inline-block; margin-right:5px;">Don't forget to check out:-</span><a href="https://www.w3web.net/" target="_blank" rel="noopener noreferrer" style="text-decoration:none;" data-aura-rendered-by="440:0">An easy way to learn step-by-step online free Salesforce tutorial, To know more Click <span style="color:#ff8000; font-size:18px;" data-aura-rendered-by="442:0">Here..</span></a></strong></p>
<br/><br/>
<p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/07/tickMarkIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:17px; font-style:italic; display:inline-block; margin-right:5px; color:rgb(255 128 0);">You May Also Like →</span> </strong></p>
<div style="display:block; overflow:hidden;">
<div style="width: 50%; float:left; display:inline-block">
<ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;">
<li><a href="https://www.w3web.net/lwc-get-set-lightning-checkbox-value/" target="_blank" rel="noopener noreferrer">How to get selected checkbox value in lwc</a></li>
<li><a href="https://www.w3web.net/display-account-related-contacts-in-lwc/" target="_blank" rel="noopener noreferrer">how to display account related contacts based on AccountId in lwc</a></li>
<li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to create lightning datatable row actions in lwc</a></li>
<li><a href="https://www.w3web.net/if-and-else-condition-in-lwc/" target="_blank" rel="noopener noreferrer">how to use if and else condition in lwc</a></li>
<li><a href="https://www.w3web.net/get-selected-radio-button-value-and-checked-default-in-lwc/" target="_blank" rel="noopener noreferrer">how to display selected radio button value in lwc</a></li>
</ul>
</div>
<div style="width: 50%; float:left; display:inline-block">
<ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;">
<li><a href="https://www.w3web.net/display-account-related-contacts-lwc/" target="_blank" rel="noopener noreferrer">display account related contacts based on account name in lwc</a></li>
<li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to insert a record of account Using apex class in LWC</a></li>
<li><a href="https://www.w3web.net/fetch-picklist-values-dynamic-in-lwc/" target="_blank" rel="noopener noreferrer">how to get picklist values dynamically in lwc</a></li>
<li><a href="https://www.w3web.net/edit-save-and-remove-rows-dynamically-in-lightning-component/" target="_blank" rel="noopener noreferrer">how to edit/save row dynamically in lightning component</a></li>
<li><a href="https://www.w3web.net/update-parent-object-from-child/" target="_blank" rel="noopener noreferrer">update parent field from child using apex trigger</a></li>
</ul>
</div>
<div style="clear:both;"></div>
<br/>
<div class="youtubeIcon">
<a href="https://www.youtube.com/channel/UCW62gTen2zniILj9xE6LmOg" target="_blank" rel="noopener noreferrer"><img src="https://www.w3web.net/wp-content/uploads/2021/11/youtubeIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;"/> <strong>TechW3web:-</strong> To know more, Use this <span style="color: #ff8000; font-weight: bold;">Link</span> </a>
</div>
</div>
</div>
<!--End RelatedTopics Section-->
</lightning-card>
</template>
Step 2:- Create Lightning Web Component : lwcCreateContactCustomLookup.js
SFDX:Lightning Web Component >> New >> lwcCreateContactCustomLookup.js
lwcCreateContactCustomLookup.js [LWC JavaScript File]
import { LightningElement, track } from 'lwc';
import { createRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { NavigationMixin } from 'lightning/navigation';
import CONTACT_OBJECT from '@salesforce/schema/Contact';
import contactFirstName from '@salesforce/schema/Contact.FirstName';
import contactLastName from '@salesforce/schema/Contact.LastName';
import contactPhone from '@salesforce/schema/Contact.Phone';
import contactEmail from '@salesforce/schema/Contact.Email';
import accountFieldId from '@salesforce/schema/Contact.AccountId';
export default class LwcCreateContactCustomLookup extends NavigationMixin(LightningElement) {
@track selectedAccountId;
@track contactId;
firstname = '';
lastname = '';
phoneNo = '';
emailId = '';
contactHandleChange(event) {
console.log(event.target.label);
console.log(event.target.value);
if(event.target.label=='First Name'){
this.firstname = event.target.value;
}
if(event.target.label=='Last Name'){
this.lastname = event.target.value;
}
if(event.target.label=='Phone'){
this.phoneNo = event.target.value;
}
if(event.target.label=='Email'){
this.emailId = event.target.value;
}
}
createLookupContactAction(){
console.log(this.selectedAccountId);
const fields = {};
fields[contactFirstName.fieldApiName] = this.firstname;
fields[contactLastName.fieldApiName] = this.lastname;
fields[contactPhone.fieldApiName] = this.phoneNo;
fields[contactEmail.fieldApiName] = this.emailId;
fields[accountFieldId.fieldApiName] = this.selectedAccountId;
const recordInput = { apiName: CONTACT_OBJECT.objectApiName, fields };
createRecord(recordInput)
.then(contactobj=> {
this.contactId = contactobj.id;
this.fields={};
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'Contact created successfully..!',
variant: 'success',
}),
);
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: contactobj.id,
objectApiName: 'Contact',
actionName: 'view'
},
});
})
.catch(error => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Error creating record',
message: error.body.message,
variant: 'error',
}),
);
});
}
myLookupHandle(event){
console.log(event.detail);
this.selectedAccountId = event.detail;
}
}
Step 3:- Create Lightning Web Component : lwcCreateContactCustomLookup.js-meta.xml
SFDX:Lightning Web Component >> New >> lwcCreateContactCustomLookup.js-meta.xml
lwcCreateContactCustomLookup.js-meta.xml [LWC Meta Data XML]
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>45.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Step 4:- Create Lightning Web Component : lwcAccountCustomLookup.html
SFDX:Lightning Web Component >> New >> lwcAccountCustomLookup.html
lwcAccountCustomLookup.html [Lightning Web Component HTML]
<template>
<lightning-card>
<div class="slds-p-horizontal_small">
<div class="row">
<div class="slds-form-element">
<div class="slds-form-element__control">
<div class="slds-combobox_container">
<div class="slds-combobox slds-dropdown-trigger slds-dropdown-trigger_click" aria-expanded="false"
aria-haspopup="listbox" role="combobox">
<div class="slds-combobox__form-element slds-input-has-icon slds-input-has-icon_right"
role="none">
<lightning-input type="search" id="combobox-id-16" value={accountName}
onchange={searchHandleKeyChange} onkeydown={searchHandleClick} onclick={searchHandleClick}
onblur={searchHandleClick} aria-activedescendant="option1" label='Account'
aria-autocomplete="list" aria-controls="listbox-id-12" role="textbox"
placeholder="Search..."></lightning-input>
</div>
<!-- Start : Parent Search Result -->
<div if:true={messageResult}>
No Result Found!
</div>
<template if:true={showSearchedValues}>
<div class="slds-box" style="height: 130px; overflow-y: scroll;">
<ul class="" role="">
<template for:each={accountList} for:item="actObj">
<li class="slds-p-around_x-small" style="cursor: pointer;" key={actObj.Id}
onclick={parentHandleAction} data-value={actObj.Id}
data-label={actObj.Name}>
{actObj.Name}
</li>
</template>
</ul>
</div>
</template>
</div>
</div>
</div>
</div>
</div>
</div>
</lightning-card>
</template>
Step 5:- Create Lightning Web Component : lwcAccountCustomLookup.js
SFDX:Lightning Web Component >> New >> lwcAccountCustomLookup.js
lwcAccountCustomLookup.js [LWC JavaScript File]
import { LightningElement, track, wire } from 'lwc';
import getCustomLookupAccount from '@salesforce/apex/lwcApexController.getCustomLookupAccount';
export default class LwcAccountCustomLookup extends LightningElement {
@track accountName='';
@track accountList=[];
@track objectApiName='Account';
@track accountId;
@track isShow=false;
@track messageResult=false;
@track isShowResult = true;
@track showSearchedValues = false;
@wire(getCustomLookupAccount,{actName:'$accountName'})
retrieveAccounts ({error,data}){
this.messageResult=false;
if(data){
console.log('data## ' + data.length);
if(data.length>0 && this.isShowResult){
this.accountList =data;
this.showSearchedValues=true;
this.messageResult=false;
}
else if(data.length == 0){
this.accountList=[];
this.showSearchedValues=false;
if(this.accountName != ''){
this.messageResult=true;
}
}
else if(error){
this.accountId='';
this.accountName='';
this.accountList=[];
this.showSearchedValues=false;
this.messageResult=true;
}
}
}
searchHandleClick(event){
this.isShowResult = true;
this.messageResult = false;
}
searchHandleKeyChange(event){
this.messageResult=false;
this.accountName = event.target.value;
}
parentHandleAction(event){
this.showSearchedValues = false;
this.isShowResult = false;
this.messageResult=false;
//Set the parent calendar id
this.accountId = event.target.dataset.value;
//Set the parent calendar label
this.accountName = event.target.dataset.label;
console.log('accountId::'+this.accountId);
const selectedEvent = new CustomEvent('selected', { detail: this.accountId });
// Dispatches the event.
this.dispatchEvent(selectedEvent);
}
}
Step 6:- Create Lightning Web Component : lwcAccountCustomLookup.js-meta.xml
SFDX:Lightning Web Component >> New >> lwcAccountCustomLookup.js-meta.xml
lwcAccountCustomLookup.js-meta.xml [LWC Meta Data XML]
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>45.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Step 7:- Create Lightning Web Component : lwcApexController.cls
SFDX:Create Apex Class >> New >> lwcApexController.cls
lwcApexController.cls[Apex Class Controller]
public WITH sharing class lwcApexController {
//custom lookup lwc
@AuraEnabled(cacheable=TRUE)
public static List<Account> getCustomLookupAccount (String actName){
List<Account> accLookupList = NEW List<Account>();
IF(actName != ''){
String accountName = '%' + actName + '%';
accLookupList = [SELECT Id, Name FROM Account WHERE Name LIKE:accountName];
RETURN accLookupList;
}
RETURN accLookupList;
}
}
Further post that would you like to learn in Salesforce
How do you display a lookup field in lightning Web component?
Use the lightning-input-field component in lightning-record-edit-form to display and edit the value of a record field of a Salesforce object. Use the field-name attribute to specify the API field name.
What is custom lookup in Salesforce?
Creates a relationship between two records so you can associate them with each other. On the parent record, you can display a related list to show all of the records that are linked to it.
On which object is the lookup relationship created?
Lookup relationship always created on Chld Object. It is a one type of relationship which form loose bond relationship between Parent object and Child object. In lookup Child record need not be associated to a parent. Lookup field is not required on the page layouts of the detail object.
Related Topics | You May Also Like
Our Free Courses →
👉 Get Free Course →
📌 Salesforce Administrators 📌 Salesforce Lightning Flow Builder 📌 Salesforce Record Trigger Flow Builder |
👉 Get Free Course →
📌 Aura Lightning Framework 📌 Lightning Web Component (LWC) 📌 Rest APIs Integration |