Create a Contact Record With Re-Usable Dynamic Custom Lookup Field in Lightning Web Component – LWC | Create contact record with custom lookup in lwc

5,248 views


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

Create a Contact Record With Re-Usable Dynamic Custom Lookup Field in Lightning Web Component -- w3web.net

 

You can download file directly from github by Click Here.

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!

 

 
 

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]

  1.   <template>
  2.     <lightning-card title="Create custom lookup on contact object" icon-name="standard:contact">
  3.         <div class="slds-p-horizontal_small">
  4.             <lightning-input label="First Name" value={firstname} onchange={contactHandleChange} class="slds-m-bottom_x-small slds-p-horizontal_small slds-form-element"></lightning-input>
  5.             <lightning-input label="Last Name" value={lastname} onchange={contactHandleChange} class="slds-m-bottom_x-small slds-p-horizontal_small slds-form-element"></lightning-input>                        
  6.             <lightning-input label="Phone" value={phone} onchange={contactHandleChange} class="slds-m-bottom_x-small slds-p-horizontal_small slds-form-element"></lightning-input>
  7.             <lightning-input label="Email" value={email} onchange={contactHandleChange} class="slds-m-bottom_x-small slds-p-horizontal_small slds-form-element"></lightning-input>            
  8.  
  9.             <c-lwc-account-custom-lookup onselected={myLookupHandle}></c-lwc-account-custom-lookup><br/>
  10.             <lightning-button label="Submit" variant="brand" onclick={createLookupContactAction} class="slds-m-bottom_x-small slds-p-horizontal_small slds-form-element"></lightning-button>                     
  11.         </div>
  12.  
  13. <br/> <br/>
  14.    <!--Start RelatedTopics Section-->
  15. <div style="border:1px #ddd solid; padding:10px; background:#eee; margin:40px 0;">
  16.  
  17.             <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>
  18.  
  19.             <br/><br/>
  20.             <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>
  21.             <div style="display:block; overflow:hidden;"> 
  22.                 <div style="width: 50%; float:left; display:inline-block">
  23.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  24.                         <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>
  25.                         <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>
  26.                         <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>
  27.                         <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>
  28.                         <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>
  29.                     </ul>
  30.             </div>
  31.  
  32.             <div style="width: 50%; float:left; display:inline-block">
  33.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  34.                         <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>
  35.                         <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>
  36.                         <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>
  37.                         <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>
  38.                         <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>
  39.                     </ul>
  40.                 </div>
  41.                <div style="clear:both;"></div> 
  42.                <br/>
  43.                 <div class="youtubeIcon">
  44.                     <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>
  45.                 </div>
  46.     </div>
  47.  
  48. </div>
  49.  
  50.   <!--End RelatedTopics Section-->
  51.  
  52. </lightning-card>
  53. </template>

Step 2:- Create Lightning Web Component : lwcCreateContactCustomLookup.js

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 

SFDX:Lightning Web Component >> New >> lwcCreateContactCustomLookup.js

lwcCreateContactCustomLookup.js [LWC JavaScript File]

  1.   import { LightningElement, track } from 'lwc';
  2. import { createRecord } from 'lightning/uiRecordApi';
  3. import { ShowToastEvent } from 'lightning/platformShowToastEvent';
  4. import { NavigationMixin } from 'lightning/navigation';
  5. import CONTACT_OBJECT from '@salesforce/schema/Contact';
  6. import contactFirstName from '@salesforce/schema/Contact.FirstName';
  7. import contactLastName from '@salesforce/schema/Contact.LastName';
  8. import contactPhone from '@salesforce/schema/Contact.Phone';
  9. import contactEmail from '@salesforce/schema/Contact.Email';
  10. import accountFieldId from '@salesforce/schema/Contact.AccountId';
  11.  
  12. export default class LwcCreateContactCustomLookup extends NavigationMixin(LightningElement) {   
  13.     @track selectedAccountId;
  14.     @track contactId;    
  15.     firstname = '';   
  16.     lastname = '';  
  17.     phoneNo = '';
  18.     emailId = '';
  19.     contactHandleChange(event) {
  20.         console.log(event.target.label);
  21.         console.log(event.target.value);        
  22.         if(event.target.label=='First Name'){
  23.             this.firstname = event.target.value;
  24.         }
  25.         if(event.target.label=='Last Name'){
  26.             this.lastname = event.target.value;
  27.         }   
  28.  
  29.         if(event.target.label=='Phone'){
  30.             this.phoneNo = event.target.value;
  31.         }
  32.  
  33.         if(event.target.label=='Email'){
  34.             this.emailId = event.target.value;
  35.         }
  36.  
  37.     }
  38.  
  39.     createLookupContactAction(){
  40.         console.log(this.selectedAccountId);
  41.         const fields = {};
  42.         fields[contactFirstName.fieldApiName] = this.firstname;
  43.         fields[contactLastName.fieldApiName] = this.lastname;
  44.         fields[contactPhone.fieldApiName] = this.phoneNo;
  45.         fields[contactEmail.fieldApiName] = this.emailId;
  46.  
  47.         fields[accountFieldId.fieldApiName] = this.selectedAccountId;
  48.         const recordInput = { apiName: CONTACT_OBJECT.objectApiName, fields };
  49.         createRecord(recordInput)
  50.             .then(contactobj=> {
  51.                 this.contactId = contactobj.id;
  52.                 this.fields={};
  53.                 this.dispatchEvent(
  54.                     new ShowToastEvent({
  55.                         title: 'Success',
  56.                         message: 'Contact created successfully..!',
  57.                         variant: 'success',
  58.                     }),
  59.                 );
  60.                 this[NavigationMixin.Navigate]({
  61.                     type: 'standard__recordPage',
  62.                     attributes: {
  63.                         recordId: contactobj.id,
  64.                         objectApiName: 'Contact',
  65.                         actionName: 'view'
  66.                     },
  67.                 });
  68.  
  69.  
  70.             })
  71.             .catch(error => {
  72.                 this.dispatchEvent(
  73.                     new ShowToastEvent({
  74.                         title: 'Error creating record',
  75.                         message: error.body.message,
  76.                         variant: 'error',
  77.                     }),
  78.                 );
  79.             });
  80.     }
  81.     myLookupHandle(event){
  82.         console.log(event.detail);
  83.         this.selectedAccountId = event.detail;
  84.     }
  85. }

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]

  1.   <?xml version="1.0" encoding="UTF-8"?>
  2. <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
  3.     <apiVersion>45.0</apiVersion>
  4.     <isExposed>true</isExposed>
  5.     <targets>
  6.         <target>lightning__AppPage</target>
  7.         <target>lightning__RecordPage</target>
  8.         <target>lightning__HomePage</target>
  9.       </targets>
  10. </LightningComponentBundle>

Step 4:- Create Lightning Web Component : lwcAccountCustomLookup.html

SFDX:Lightning Web Component >> New >> lwcAccountCustomLookup.html

lwcAccountCustomLookup.html [Lightning Web Component HTML]

  1.   <template>
  2.     <lightning-card>
  3.         <div class="slds-p-horizontal_small">
  4.             <div class="row">
  5.                 <div class="slds-form-element">
  6.                     <div class="slds-form-element__control">
  7.                         <div class="slds-combobox_container">
  8.                             <div class="slds-combobox slds-dropdown-trigger slds-dropdown-trigger_click" aria-expanded="false"
  9.                                 aria-haspopup="listbox" role="combobox">
  10.                                 <div class="slds-combobox__form-element slds-input-has-icon slds-input-has-icon_right"
  11.                                     role="none">
  12.                                     <lightning-input type="search" id="combobox-id-16" value={accountName}
  13.                                         onchange={searchHandleKeyChange} onkeydown={searchHandleClick} onclick={searchHandleClick}
  14.                                         onblur={searchHandleClick} aria-activedescendant="option1" label='Account'
  15.                                         aria-autocomplete="list" aria-controls="listbox-id-12" role="textbox"
  16.                                         placeholder="Search..."></lightning-input>   
  17.                                 </div>
  18.                                 <!-- Start : Parent Search Result -->
  19.                                 <div if:true={messageResult}>
  20.                                     No Result Found!
  21.                                 </div>
  22.                                 <template if:true={showSearchedValues}>
  23.                                     <div class="slds-box" style="height: 130px; overflow-y: scroll;">
  24.                                         <ul class="" role="">
  25.                                             <template for:each={accountList} for:item="actObj">
  26.                                                 <li class="slds-p-around_x-small" style="cursor: pointer;" key={actObj.Id}
  27.                                                     onclick={parentHandleAction} data-value={actObj.Id}
  28.                                                     data-label={actObj.Name}>
  29.                                                     {actObj.Name}
  30.                                                 </li>
  31.                                             </template>
  32.                                         </ul>
  33.                                     </div>
  34.                                 </template>
  35.                             </div>
  36.                         </div>
  37.  
  38.                     </div>
  39.                 </div>
  40.             </div>
  41.         </div>
  42.  
  43.         </lightning-card>  
  44. </template>

Step 5:- Create Lightning Web Component : lwcAccountCustomLookup.js

SFDX:Lightning Web Component >> New >> lwcAccountCustomLookup.js

lwcAccountCustomLookup.js [LWC JavaScript File]

  1.    import { LightningElement, track, wire } from 'lwc';
  2. import getCustomLookupAccount from '@salesforce/apex/lwcApexController.getCustomLookupAccount';
  3.  
  4. export default class LwcAccountCustomLookup extends LightningElement {
  5.  
  6.  @track accountName='';
  7.  @track accountList=[];
  8.  @track objectApiName='Account';
  9.  @track accountId;
  10.  @track isShow=false;
  11.  @track messageResult=false;
  12.  @track isShowResult = true;
  13.  @track showSearchedValues = false;
  14.  @wire(getCustomLookupAccount,{actName:'$accountName'})
  15.  retrieveAccounts ({error,data}){
  16.      this.messageResult=false;
  17.      if(data){
  18.          console.log('data## ' + data.length);
  19.          if(data.length>0 && this.isShowResult){
  20.             this.accountList =data;
  21.             this.showSearchedValues=true;
  22.             this.messageResult=false;
  23.          }
  24.          else if(data.length == 0){
  25.             this.accountList=[];
  26.             this.showSearchedValues=false;
  27.             if(this.accountName != ''){
  28.                this.messageResult=true;
  29.             }
  30.          }
  31.          else if(error){
  32.              this.accountId='';
  33.              this.accountName='';
  34.              this.accountList=[];
  35.              this.showSearchedValues=false;
  36.              this.messageResult=true;
  37.          }
  38.  
  39.      }
  40.  }
  41.  
  42.  
  43.  
  44.  searchHandleClick(event){
  45.   this.isShowResult = true;
  46.   this.messageResult = false;
  47. }
  48.  
  49.  
  50. searchHandleKeyChange(event){
  51.   this.messageResult=false;
  52.   this.accountName = event.target.value;
  53. }
  54.  
  55. parentHandleAction(event){        
  56.     this.showSearchedValues = false;
  57.     this.isShowResult = false;
  58.     this.messageResult=false;
  59.     //Set the parent calendar id
  60.     this.accountId =  event.target.dataset.value;
  61.     //Set the parent calendar label
  62.     this.accountName =  event.target.dataset.label;      
  63.     console.log('accountId::'+this.accountId);    
  64.     const selectedEvent = new CustomEvent('selected', { detail: this.accountId });
  65.         // Dispatches the event.
  66.     this.dispatchEvent(selectedEvent);    
  67. }
  68.  
  69. }

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]

  1.    <?xml version="1.0" encoding="UTF-8"?>
  2. <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
  3.     <apiVersion>45.0</apiVersion>
  4.     <isExposed>true</isExposed>
  5.     <targets>
  6.         <target>lightning__AppPage</target>
  7.         <target>lightning__RecordPage</target>
  8.         <target>lightning__HomePage</target>
  9.       </targets>
  10. </LightningComponentBundle>

Step 7:- Create Lightning Web Component : lwcApexController.cls

SFDX:Create Apex Class >> New >> lwcApexController.cls

lwcApexController.cls[Apex Class Controller]

  1.   public WITH sharing class lwcApexController {
  2.  
  3.     //custom lookup lwc
  4. @AuraEnabled(cacheable=TRUE)
  5. public static List<Account> getCustomLookupAccount (String actName){
  6.    List<Account> accLookupList =  NEW List<Account>();
  7.    IF(actName != ''){
  8.        String accountName = '%' + actName + '%';
  9.        accLookupList = [SELECT Id, Name FROM Account WHERE Name LIKE:accountName];
  10.        RETURN accLookupList;
  11.    }
  12.    RETURN accLookupList;
  13. }   
  14.  
  15. }

Create a Contact Record With Re-Usable Dynamic Custom Lookup Field in Lightning Web Component -- w3web.net

Further post that would you like to learn in Salesforce

 

 

FAQ (Frequently Asked Questions)

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

 
Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 
  

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



Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net

Leave a Comment