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.
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
You can download file directly from github by Click Here.
Other related post that would you like to learn in Salesforce
Note:- Custom sObject >> NewStudent__c
You need to change my custom sObject name with your custom sObject name.
Step 1:-
Lightning Component [myCustomLookupCmp.cmp]
<aura:component controller="myLookupController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
<aura:attribute name="studentReg" type="Registration__c" default="{'sobjectType':'Registration__c','DateOfRegistration__c':'mm/dd/yyyy'}"/>
<aura:attribute name="studentNameItems" type="Object[]" />
<aura:attribute name="selectedSerchItem" type="string"/>
<aura:attribute name="selectedItemId" type="string"/>
<div class="slds">
<div class="slds-p-horizontal--medium slds-col slds-size_6-of-12 slds-m-bottom--medium">
<div class="slds-form-element">
<label class="slds-form-element__label">New Student</label>
<div class="slds-form-element__controller">
<div aura:id="newStudentSpinId" class="slds-input-has-icon slds-input-has-icon--right spinnerItem">
<ui:inputText aura:id="newStudentId" placeholder="Search student..." class="slds-input" keyup="{!c.lookupKeySearch}" updateOn="keyup" value="{!v.studentReg.RegNewStudent__c}"/>
<i class="spinnerIcon" ><img src="/resource/SLDS2016/assets/images/spinners/slds_spinner_brand.gif" /></i>
<c:svg class="slds-input__icon" xlinkHref="/resource/SLDS2016/assets/icons/utility-sprite/svg/symbols.svg#search"/>
</div>
<!--{!v.studentReg.RegNewStudent_#c.length}{!v.studentNameItems}<br/>-->
<div aura:id="sldsIsOpenDivId" class="slds-m-top--small slds-dropdown-trigger slds-dropdown-trigger--click dropdownPosition">
<section class="slds-dropdown slds-popover slds-nubbin--top-left slds-dropdown-trigger">
<div class="slds-popover__body slds-p-vertical--xx-small slds-p-horizontal--none slds-scrollable--y" style="max-height:150px;">
<ul class="slds-dropdown__list slds-dropdown--length10">
<aura:iteration items="{!v.studentNameItems}" var="studentVar" indexVar="goNumber">
<li>
<span class="slds-lookup__item-action slds-media">
<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" />
<a id="{!studentVar.Id}" role="option"
data-id="{!studentVar.Id}" onclick="{!c.selectSearchItem}">
{!studentVar.Name}
</a>
</span>
</li>
</aura:iteration>
</ul>
</div>
</section>
</div>
<div aura:id="pillListDivId" class="slds-hide">
<ul>
<li class="slds-pill slds-show slds-show slds-m-around--none" >
<a id="" role="option" onclick="{!c.removeSelectedSerchItem}" data-id="">
<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" />
{!v.selectedSerchItem}
<button class="slds-button slds-butto--icon slds-float--right slds-pill__remove slds-m-top--xx-small" style="line-height:1.45rem;">
<c:svg class="slds-button__icon" xlinkHref="/resource/SLDS2016/assets/icons/utility-sprite/svg/symbols.svg#close" />
</button>
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="slds-text-align--center slds-m-top--medium">
<button class="slds-button slds-button--brand" onclick="{!c.submitRegAction}">Submit</button>
</div>
</div>
<br/><br/>
<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>
</div>
</aura:component>
Step 2:-
JS Controller [myCustomLookupCmpController.js]
({
lookupKeySearch : function(component, event, helper) {
var searchStr = event.getSource().get("v.value");
//alert('searchStr ' + searchStr);
var newStudentSpinId = component.find('newStudentSpinId');
var sldsIsOpenDivId = component.find('sldsIsOpenDivId');
var newStudentId = component.find('newStudentId');
var getStudentVal = component.get('v.studentReg.RegNewStudent__c');
$A.util.addClass(newStudentSpinId, 'spinner');
$A.util.addClass(sldsIsOpenDivId,'slds-is-open');
if(!$A.util.isUndefinedOrNull(getStudentVal) && searchStr.length>2){
var action = component.get('c.regStudenMethd');
//alert('action ' + action);
action.setParams({'searchStudent':searchStr});
action.setCallback(this, function(response){
var state = response.getState();
if(state == "SUCCESS"){
var result = response.getReturnValue();
component.set('v.studentNameItems', result);
//alert(JSON.stringify(component.get('v.studentNameItems')));
$A.util.removeClass(newStudentSpinId, 'spinner');
//alert('datd populated successfully');
}
});
$A.enqueueAction(action);
}
},
selectSearchItem:function(component, event, helper){
var thisObj = event.currentTarget.innerText;
var thisId = event.target.id;
//alert(thisId);
var pillListDivId = component.find('pillListDivId');
var newStudentSpinId = component.find('newStudentSpinId');
component.set('v.selectedSerchItem',thisObj); //selectedItemId
component.set('v.selectedItemId',thisId);
//alert('select'+component.get('v.selectedItemId'));
$A.util.removeClass(pillListDivId,'slds-hide');
$A.util.addClass(newStudentSpinId, 'slds-hide');
},
removeSelectedSerchItem:function(component, event, helper){
var sldsIsOpenDivId = component.find('sldsIsOpenDivId');
var pillListDivId = component.find('pillListDivId');
var newStudentSpinId = component.find('newStudentSpinId');
$A.util.removeClass(sldsIsOpenDivId,'slds-is-open');
$A.util.addClass(pillListDivId,'slds-hide');
$A.util.removeClass(newStudentSpinId, 'slds-hide');
component.set('v.studentReg.RegNewStudent__c','');
},
submitRegAction:function(component, event, helper){
var isValid = true;
var newStudentId = component.find('newStudentId');
var newStudentIdVal = component.find('newStudentId').get('v.value');
//var searchStr = event.getSource().get("v.value");
if($A.util.isUndefinedOrNull(newStudentIdVal) || $A.util.isEmpty(newStudentIdVal)){
isValid = false;
newStudentId.set("v.errors",[{message:'Student name is required'}]);
}else{
newStudentId.set("v.errors",null);
}
if(isValid){
var action = component.get('c.regSaveDataMthd');
var selectedId = component.get('v.selectedItemId');
//alert('selectedId:: '+selectedId+' @@@ '+dateval);
action.setParams({
'masterId':selectedId
});
action.setCallback(this, function(response){
var state = response.getState();
//alert(state);
if(state == "SUCCESS"){
var result = response.getReturnValue();
//alert('Record saved successfully');
var sldsIsOpenDivId = component.find('sldsIsOpenDivId');
var pillListDivId = component.find('pillListDivId');
var newStudentSpinId = component.find('newStudentSpinId');
$A.util.removeClass(sldsIsOpenDivId,'slds-is-open');
$A.util.addClass(pillListDivId,'slds-hide');
$A.util.removeClass(newStudentSpinId, 'slds-hide');
component.set('v.studentReg.RegNewStudent__c','');
component.set('v.selectedItemId','');
var courseSpinId = component.find('courseSpinId');
var courseOpenDivId = component.find('courseOpenDivId');
var coursePillListDivId = component.find('coursePillListDivId');
component.set('v.studentReg.RegCourse__c', '');
$A.util.removeClass(courseSpinId, 'slds-hide');
$A.util.removeClass(courseOpenDivId, 'slds-is-open');
$A.util.addClass(coursePillListDivId, 'slds-hide');
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
'title':'Success',
'type':'Success',
'message':'The record has been updated successfully.'
});
toastEvent.fire();
}
});
$A.enqueueAction(action);
}
},
})
Step 3:-
Componrnt CSS [myCustomLookupCmp.css]
.THIS {
}
.THIS .spinnerItem .spinnerIcon{display:none;}
.THIS .spinnerItem.spinner .spinnerIcon{position:absolute; position: absolute; right: 5px; top: 6px; width: 20px; height:20px; display:block; }
.THIS .spinnerItem.spinner .slds-input__icon{display:none;}
.THIS .spinnerItem.slds-hide + .slds-dropdown-trigger{display:none;}
.THIS .dropdownPosition{position:absolute; left:-90px; top: 55px; right:0;}
Step 4:-
Apex Class [myLookupController.apxc]
public class myLookupController {
@AuraEnabled
public static List regStudenMethd(string searchStudent){
searchStudent = '%' + searchStudent + '%';
List getSrhStudentList = [SELECT id,Name FROM NewStudent__c WHERE Name LIKE:searchStudent ];
RETURN getSrhStudentList;
}
@AuraEnabled
public static void regSaveDataMthd(string masterId){
Registration__c regPostData = NEW Registration__c();
regPostData.RegNewStudent__c =masterId;
INSERT regPostData;
}
}
Note:-Static resource zip file
You need to change $Resource.SLDS2016 with your SLDS zip file name (static resource zip file Name)
<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
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
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 |