How to create custom lookup on custom object in lightning component | how to create custom lookup dynamically as re-usable in Salesforce lightning component

2,226 views


Hey guys, today in this post we are going to learn about how to create custom lookup on custom object and submit the lookup value into database in lightning component.

What is lookup relationship in Salesforce?

Lookup relationship communicate between two objects. First known as Parent Object and Second Known as Child Object.

It is always created on child object. Some time we are working on child object and need to fetch the value of parent object.

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

In this case we need to create a lookup relationship. It will help to fetch the value of parent object.

Lookup relationship field does not required. If parent record deleted then it’s associated child record does not deleted.

We used the files in this example

File Name File Type Description
myCustomLookupCmp.cmp Lightning Component It is used to user interface display on the client side.
myCustomLookupCmpController.js Component JS It is used for communicate the javascript function to apex class method.
myCustomLookupCmp.css CSS For alignment the lookup popover box.
myLookupController.apxc Apex Class Controller For fetch the record value from database server
SVG Icon Image Search Icon Image Lightning Icon Reference :https://www.lightningdesignsystem.com/icons/
static resource Zip file Use for display the Icon from static resource

Final Output

custom lookup on custom object in lightning component -- w3web.net

 

You can download file directly from github by Click Here.

 

Other related post that would you like to learn in Salesforce

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

 

Note:- Custom sObject >> NewStudent__c

You need to change my custom sObject name with your custom sObject name.

Step 1:-

Lightning Component [myCustomLookupCmp.cmp]

  1.    <aura:component controller="myLookupController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
  2.  
  3.  
  4.     <aura:attribute name="studentReg" type="Registration__c" default="{'sobjectType':'Registration__c','DateOfRegistration__c':'mm/dd/yyyy'}"/>
  5.     <aura:attribute name="studentNameItems" type="Object[]" />
  6.     <aura:attribute name="selectedSerchItem" type="string"/>
  7.     <aura:attribute name="selectedItemId" type="string"/>
  8.  
  9.  
  10.     <div class="slds">
  11.         <div class="slds-p-horizontal--medium slds-col slds-size_6-of-12 slds-m-bottom--medium">
  12.             <div class="slds-form-element">
  13.                 <label class="slds-form-element__label">New Student</label>
  14.                 <div class="slds-form-element__controller">
  15.                     <div aura:id="newStudentSpinId" class="slds-input-has-icon slds-input-has-icon--right spinnerItem">
  16.                         <ui:inputText aura:id="newStudentId" placeholder="Search student..." class="slds-input" keyup="{!c.lookupKeySearch}" updateOn="keyup" value="{!v.studentReg.RegNewStudent__c}"/>
  17.                         <i class="spinnerIcon" ><img src="/resource/SLDS2016/assets/images/spinners/slds_spinner_brand.gif" /></i>
  18.                         <c:svg class="slds-input__icon" xlinkHref="/resource/SLDS2016/assets/icons/utility-sprite/svg/symbols.svg#search"/>
  19.                     </div> 
  20.  
  21.  
  22.                     <!--{!v.studentReg.RegNewStudent_#c.length}{!v.studentNameItems}<br/>-->
  23.                     <div aura:id="sldsIsOpenDivId" class="slds-m-top--small slds-dropdown-trigger slds-dropdown-trigger--click dropdownPosition"> 
  24.  
  25.                         <section class="slds-dropdown slds-popover slds-nubbin--top-left slds-dropdown-trigger"> 
  26.                             <div class="slds-popover__body slds-p-vertical--xx-small slds-p-horizontal--none slds-scrollable--y" style="max-height:150px;"> 
  27.                                 <ul class="slds-dropdown__list slds-dropdown--length10">
  28.                                     <aura:iteration items="{!v.studentNameItems}" var="studentVar" indexVar="goNumber">
  29.                                         <li>
  30.                                             <span class="slds-lookup__item-action slds-media"> 
  31.                                                 <c:svg class="slds-icon slds-icon-standard-contact slds-icon--small slds-m-right--xx-small"  xlinkHref="/resource/SLDS2016/assets/icons/utility-sprite/svg/symbols.svg#user" />
  32.                                                 <a id="{!studentVar.Id}" role="option" 
  33.                                                    data-id="{!studentVar.Id}" onclick="{!c.selectSearchItem}">                                                    
  34.                                                     {!studentVar.Name}
  35.                                                 </a>
  36.                                             </span>   
  37.  
  38.                                         </li>
  39.  
  40.                                     </aura:iteration>      
  41.                                 </ul>
  42.                             </div> 
  43.                         </section>
  44.  
  45.                     </div>
  46.  
  47.  
  48.                     <div aura:id="pillListDivId" class="slds-hide">
  49.                         <ul> 
  50.                             <li class="slds-pill slds-show slds-show slds-m-around--none" >
  51.                                 <a  id="" role="option" onclick="{!c.removeSelectedSerchItem}" data-id="">
  52.                                     <c:svg class="slds-icon slds-icon-standard-contact slds-icon--small slds-m-right--xx-small" xlinkHref="/resource/SLDS2016/assets/icons/utility-sprite/svg/symbols.svg#user" />
  53.                                     {!v.selectedSerchItem}
  54.                                     <button class="slds-button slds-butto--icon slds-float--right slds-pill__remove slds-m-top--xx-small" style="line-height:1.45rem;">
  55.                                         <c:svg class="slds-button__icon" xlinkHref="/resource/SLDS2016/assets/icons/utility-sprite/svg/symbols.svg#close" />
  56.                                     </button>     
  57.                                 </a>
  58.                             </li>      
  59.                         </ul>
  60.                     </div>
  61.  
  62.                 </div>
  63.             </div> 
  64.  
  65.             <div class="slds-text-align--center slds-m-top--medium">
  66.                 <button class="slds-button slds-button--brand" onclick="{!c.submitRegAction}">Submit</button>
  67.             </div>
  68.  
  69.  
  70.         </div>       
  71.  
  72. <br/><br/>
  73. <p><img src="https://www.w3web.net/wp-content/uploads/2021/05/thumbsUpLike.png" width="25" height="25" style="vertical-align:top; margin-right:10px;"/> <strong> <span style="font-size:15px; font-style:italic; display:inline-block; margin-right:5px;">Don't forget to check out:-</span> <a href="https://www.w3web.net/" target="_blank" style="text-decoration:none;" rel="noopener noreferrer">An easy way to learn step-by-step online free tutorial, To know more Click  <span style="color:#ff8000; font-size:18px;">Here..</span></a></strong></p>
  74.  
  75.  
  76.     </div>
  77.  
  78. </aura:component>

Step 2:-

JS Controller [myCustomLookupCmpController.js]

  1.    ({
  2. 	lookupKeySearch : function(component, event, helper) {
  3. 		var searchStr = event.getSource().get("v.value");  
  4.         //alert('searchStr ' + searchStr);
  5.         var newStudentSpinId = component.find('newStudentSpinId');
  6.         var sldsIsOpenDivId = component.find('sldsIsOpenDivId');
  7.         var newStudentId = component.find('newStudentId');
  8.         var getStudentVal = component.get('v.studentReg.RegNewStudent__c');
  9.         $A.util.addClass(newStudentSpinId, 'spinner');
  10.         $A.util.addClass(sldsIsOpenDivId,'slds-is-open');
  11.         if(!$A.util.isUndefinedOrNull(getStudentVal) &amp;&amp; searchStr.length&gt;2){
  12.             var action = component.get('c.regStudenMethd');
  13.             //alert('action ' + action);
  14.             action.setParams({'searchStudent':searchStr});
  15.             action.setCallback(this, function(response){
  16.                 var state = response.getState();
  17.                 if(state == "SUCCESS"){
  18.                     var result = response.getReturnValue();
  19.                     component.set('v.studentNameItems', result);
  20.                     //alert(JSON.stringify(component.get('v.studentNameItems')));
  21.                      $A.util.removeClass(newStudentSpinId, 'spinner');
  22.                     //alert('datd populated successfully');
  23.                 }
  24.             });
  25.             $A.enqueueAction(action);
  26.         }
  27.  
  28.  
  29. 	},
  30.  
  31.     selectSearchItem:function(component, event, helper){
  32.         var thisObj = event.currentTarget.innerText;
  33.         var thisId = event.target.id;
  34.       //alert(thisId);
  35.  
  36.         var pillListDivId = component.find('pillListDivId');
  37.         var newStudentSpinId = component.find('newStudentSpinId');
  38.         component.set('v.selectedSerchItem',thisObj); //selectedItemId
  39.         component.set('v.selectedItemId',thisId);
  40.         //alert('select'+component.get('v.selectedItemId'));
  41.  
  42.         $A.util.removeClass(pillListDivId,'slds-hide');
  43.         $A.util.addClass(newStudentSpinId, 'slds-hide');
  44.     },
  45.  
  46.  
  47.     removeSelectedSerchItem:function(component, event, helper){
  48.  
  49.         var sldsIsOpenDivId = component.find('sldsIsOpenDivId');
  50.         var pillListDivId = component.find('pillListDivId');
  51.         var newStudentSpinId = component.find('newStudentSpinId');
  52.  
  53.         $A.util.removeClass(sldsIsOpenDivId,'slds-is-open');
  54.         $A.util.addClass(pillListDivId,'slds-hide');
  55.         $A.util.removeClass(newStudentSpinId, 'slds-hide'); 
  56.         component.set('v.studentReg.RegNewStudent__c','');
  57.  
  58.     },
  59.  
  60.  
  61.     submitRegAction:function(component, event, helper){
  62.  
  63.         var isValid = true;
  64.         var newStudentId = component.find('newStudentId');
  65.         var newStudentIdVal = component.find('newStudentId').get('v.value');
  66.  
  67.         //var searchStr = event.getSource().get("v.value");
  68.  
  69.  
  70.         if($A.util.isUndefinedOrNull(newStudentIdVal) || $A.util.isEmpty(newStudentIdVal)){
  71.             isValid = false;
  72.             newStudentId.set("v.errors",[{message:'Student name is required'}]);
  73.         }else{
  74.             newStudentId.set("v.errors",null);
  75.         }
  76.  
  77.         if(isValid){
  78.         var action = component.get('c.regSaveDataMthd');
  79.         var selectedId = component.get('v.selectedItemId');
  80.  
  81.         //alert('selectedId:: '+selectedId+'  @@@  '+dateval);
  82.             action.setParams({
  83.                 'masterId':selectedId                
  84.             });
  85.             action.setCallback(this, function(response){
  86.  
  87.                var state = response.getState();       
  88.                  //alert(state);
  89.                 if(state == "SUCCESS"){
  90.                     var result = response.getReturnValue();
  91.  
  92.                     //alert('Record saved successfully');
  93.  
  94.  
  95.                     var sldsIsOpenDivId = component.find('sldsIsOpenDivId');
  96.                     var pillListDivId = component.find('pillListDivId');
  97.                     var newStudentSpinId = component.find('newStudentSpinId');
  98.  
  99.                     $A.util.removeClass(sldsIsOpenDivId,'slds-is-open');
  100.                     $A.util.addClass(pillListDivId,'slds-hide');
  101.                     $A.util.removeClass(newStudentSpinId, 'slds-hide'); 
  102.                     component.set('v.studentReg.RegNewStudent__c','');                          
  103.                     component.set('v.selectedItemId','');
  104.  
  105.                     var courseSpinId = component.find('courseSpinId');
  106.                     var courseOpenDivId = component.find('courseOpenDivId');
  107.                     var coursePillListDivId = component.find('coursePillListDivId');
  108.                     component.set('v.studentReg.RegCourse__c', '');
  109.                     $A.util.removeClass(courseSpinId, 'slds-hide');
  110.                     $A.util.removeClass(courseOpenDivId, 'slds-is-open');
  111.                     $A.util.addClass(coursePillListDivId, 'slds-hide');
  112.  
  113.                     var toastEvent = $A.get("e.force:showToast");
  114.                     toastEvent.setParams({
  115.                         'title':'Success',
  116.                         'type':'Success',
  117.                         'message':'The record has been updated successfully.'
  118.                     });
  119.                     toastEvent.fire();
  120.  
  121.                 }
  122.  
  123.             });
  124.             $A.enqueueAction(action);
  125.         } 
  126.  
  127.     },
  128.  
  129.  
  130.  
  131. })

Step 3:-

Componrnt CSS [myCustomLookupCmp.css]

  1.    .THIS {
  2. }
  3. .THIS .spinnerItem .spinnerIcon{display:none;}
  4. .THIS .spinnerItem.spinner .spinnerIcon{position:absolute; position: absolute; right: 5px; top: 6px; width: 20px; height:20px;  display:block; }
  5. .THIS .spinnerItem.spinner .slds-input__icon{display:none;}
  6.  
  7. .THIS .spinnerItem.slds-hide + .slds-dropdown-trigger{display:none;}
  8. .THIS .dropdownPosition{position:absolute; left:-90px; top: 55px; right:0;}

Step 4:-

Apex Class [myLookupController.apxc]

  1.    public class myLookupController {
  2.  
  3.     @AuraEnabled
  4.     public static List regStudenMethd(string searchStudent){
  5.         searchStudent = '%' + searchStudent + '%';
  6.          List getSrhStudentList = [SELECT id,Name FROM NewStudent__c WHERE Name LIKE:searchStudent ];
  7.         RETURN getSrhStudentList;
  8.     } 
  9.  
  10.     @AuraEnabled
  11.     public static void regSaveDataMthd(string masterId){        
  12.         Registration__c regPostData = NEW Registration__c();
  13.         regPostData.RegNewStudent__c =masterId;        
  14.         INSERT regPostData;
  15.     }
  16.  
  17. }

Note:-Static resource zip file

You need to change $Resource.SLDS2016 with your SLDS zip file name (static resource zip file Name)

  1.  <button class="slds-button slds-butto--icon slds-float--right slds-pill__remove slds-m-top--xx-small" style="line-height: 1.45rem;"></button>

 

 

Further post that would you like to learn in Salesforce

 
 

 

 

FAQ (Frequently Asked Questions)

Can we create the lookup relation on the standard object in Salesforce?

When you define a lookup relationship, you can include a lookup field on the page layouts for that object and create a related list on the associated object's page layouts.

What are custom report types?

Custom Report Types (CRT) gives Salesforce administrators the ability to create dynamic reports that go beyond the ability Standard Reports have. Think of Standard Reports as a canned reporting tool that is provided by Salesforce.

What is difference between master detail and lookup?

The Salesforce lookup relationship has no relation with other records. It does not depend on any other objects, whereas a master-detail relationship has an association with other records. On the other hand, the lookup relationship is just a reference. It can be even blank or NULL.

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