This article references :http://sfdcmonkey.com/2017/01/07/custom-lookup-lightning-component/, In reference to demo Simple changes and optimizations have been made in .

We are https://www.cnblogs.com/zero-zyq/p/7463016.html  Use in jquery Of DataTable It's like an enhanced version Lookup Component effect , adopt Name You can search out the specified data , Select to get the selected object And ID Information . The main content of this article is lightning Next use aura The common use of the frame Lookup Implementation of components .

The components in this article mainly have the following functions :

1. When more than two characters are entered , Retrieve from the background database and display in the search box list ;

2. When a specified cell in the search box list is selected , The selected cells will be displayed in pill In the input box , At the same time, the input box is hidden , List selection box hidden ;

3. After deleting the selected cell , The input box becomes available .

The implementation is as follows :

1. First of all, will slds The folder of is in static resource in ,demo The path in is :slds_resource. The path of the downloaded file is :https://www.lightningdesignsystem.com/downloads/

The structure of package opening is as follows :

2. establish svg.component, Used for display slds Provided icon

svg.component

 <aura:component >
<aura:attribute name="class" type="String" description="CSS classname for the SVG element" />
<aura:attribute name="xlinkHref" type="String" description="SLDS icon path. Ex: /icons/utility-sprite/svg/symbols.svg#download" />
<aura:attribute name="aria-hidden" type="String" default="true" description="aria-hidden true or false. defaults to true" />
</aura:component>

svgRenderer.js

 ({
render: function(component, helper) {
var classname = component.get("v.class");
var xlinkhref = component.get("v.xlinkHref");
var ariaHidden = component.get("v.aria-hidden"); var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('class', classname);
svg.setAttribute('aria-hidden', ariaHidden);
svg.innerHTML = '<use xlink:href="'+xlinkhref+'"></use>';
return svg;
}
})

3. selectedObjectEvent.evt: It is used when a specified cell is selected in the searched list , Pass to the parent component .

 <aura:event type="COMPONENT" description=" pass the selected sObject in the parent component">
<aura:attribute name="objectByEvent" type="sObject"/>
</aura:event>

4. customLookUpResult.cmp: The presentation component for each unit that displays the results of the search , When the unit is selected, the above event is triggered .

 <aura:component >
<aura:attribute name="selectedObj" type="sObject" />
<aura:registerEvent name="selectedObjectEvent" type="c:selectedObjectEvent"/>
<li role="presentation">
<span class="slds-lookup__item-action slds-media slds-media--center" role="option">
<div class="slds-media__body">
<div class="slds-lookup__result-text" onclick="{!c.selectObject}">{!v.selectedObj.Name}
</div>
</div>
</span>
</li>
</aura:component>

customLookUpResultController.js

 ({
selectObject : function(component, event, helper){
var selectedObject = component.get("v.selectedObj");
var compEvent = component.getEvent("selectedObjectEvent");
compEvent.setParams({"objectByEvent" : selectedObject});
compEvent.fire();
}
})

5. customLookUp.cmp : It mainly includes several parts :

  • According to what was passed on object Of API Name obtain Label Dynamic display of search object Of Label Information ;
  • Show search buttons , Trigger after search controller Of handler To control the display of the background result set ;
  • When searching spinner Show and hide ;
  • After removing the selected cell , Enable input status, etc .
 <aura:component controller="lookUpController" implements="flexipage:availableForAllPageTypes,force:appHostable,flexipage:availableForRecordHome,force:lightningQuickActionWithoutHeader,force:hasRecordId">
<ltng:require styles="{!$Resource.slds_resource + '/styles/salesforce-lightning-design-system.css'}"/>
<aura:attribute name="selectedRecord" type="sObject" description="store selected sObject information"/>
<aura:attribute name="objectType" type="String" description="store object type"/>
<aura:attribute name="objectLabel" type="String" description="store object label name"/>
<aura:attribute name="searchObjList" type="sObject[]" description="store sObject list, this list return from apex fetched"/>
<aura:attribute name="SearchKeyWord" type="string"/>
<aura:attribute name="Message" type="String" default="Searching..."/>
<aura:handler name="selectedObjectEvent" event="c:selectedObjectEvent" action="{!c.selectedObjectHandler}"/>
<aura:handler event="aura:waiting" action="{!c.showSpinner}"/>
<aura:handler event="aura:doneWaiting" action="{!c.hideSpinner}"/>
<aura:handler name="init" value="{!this}" action="{!c.initialData}"/>
<div class="slds-m-around--large">
<div aura:id="searchRes" class="slds-form-element slds-lookup slds-is-close" data-select="single">
<label class="slds-form-element__label" for="resultListDiv"> {!v.objectLabel} Name</label> <div class="slds-form-element__control">
<div class="slds-input-has-icon slds-input-has-icon--right">
<c:svg class="slds-input__icon slds-show" xlinkHref="{!$Resource.slds_resource + '/icons/utility-sprite/svg/symbols.svg#search'}" /> <div aura:id="lookup-pill" class="slds-pill-container slds-hide">
<span class="slds-pill">
<span class="slds-pill__label">
{!v.selectedRecord.Name}
</span>
<button class="slds-button slds-button--icon slds-pill__remove" onclick="{!c.clearSelectedHandler}">
<c:svg class="slds-button__icon" xlinkHref="{!$Resource.slds_resource + '/icons/utility-sprite/svg/symbols.svg#close'}" />
<span class="slds-assistive-text">Remove</span>
</button>
</span>
</div>
<div aura:id="lookupField" class="slds-show">
<ui:inputText updateOn="keyup" keyup="{!c.fetchResultHandler}" class="slds-lookup__search-input slds-input " value="{!v.SearchKeyWord}" placeholder="must search more than 2 character" aura:id="searchValue"/>
</div>
</div>
</div> <div class="slds-lookup__menu slds" id="resultListDiv">
<div class="slds-lookup__item--label slds-text-body--small">{!v.Message}</div>
<center> <ui:spinner aura:id="spinner"/> </center>
<ul class="slds-lookup__list" role="listbox">
<aura:iteration items="{!v.searchObjList}" var="singleRec">
<c:customLookupResult selectedObj="{!singleRec}" />
</aura:iteration>
</ul>
</div>
</div>
</div>
</aura:component>

customLookUpController.js

 ({
initialData : function(component,event,helper) {
var action = component.get('c.getObjectLabelByObjectName');
action.setParam('objName', component.get('v.objectType'));
action.setCallback(this, function(response) {
if(response.getState() === 'SUCCESS') {
component.set('v.objectLabel', response.getReturnValue());
}
});
$A.enqueueAction(action);
}, fetchResultHandler : function(component, event, helper) {
var keyWord = component.get("v.SearchKeyWord");
var resultListDiv = component.find("searchRes");
if( keyWord.length > 2){
$A.util.addClass(resultListDiv, 'slds-is-open');
$A.util.removeClass(resultListDiv, 'slds-is-close');
helper.searchHelper(component,event,keyWord);
}
else{
component.set("v.searchObjList", null );
$A.util.addClass(resultListDiv, 'slds-is-close');
$A.util.removeClass(resultListDiv, 'slds-is-open');
}
}, clearSelectedHandler :function(component,event,heplper){ var pillTarget = component.find("lookup-pill");
var lookUpTarget = component.find("lookupField"); $A.util.addClass(pillTarget, 'slds-hide');
$A.util.removeClass(pillTarget, 'slds-show'); $A.util.addClass(lookUpTarget, 'slds-show');
$A.util.removeClass(lookUpTarget, 'slds-hide'); component.set("v.SearchKeyWord",null);
component.set("v.searchObjList", null );
}, selectedObjectHandler : function(component, event, helper) { var selectedObject = event.getParam("objectByEvent");
component.set("v.selectedRecord" , selectedObject);
var pillDiv = component.find("lookup-pill");
$A.util.addClass(pillDiv, 'slds-show');
$A.util.removeClass(pillDiv, 'slds-hide'); var resultListDiv = component.find("searchRes");
$A.util.addClass(resultListDiv, 'slds-is-close');
$A.util.removeClass(resultListDiv, 'slds-is-open'); var lookUpTarget = component.find("lookupField");
$A.util.addClass(lookUpTarget, 'slds-hide');
$A.util.removeClass(lookUpTarget, 'slds-show'); }, hideSpinner : function (component, event, helper) {
var spinner = component.find('spinner');
var evt = spinner.get("e.toggle");
evt.setParams({ isVisible : false });
evt.fire();
}, showSpinner : function (component, event, helper) {
var spinner = component.find('spinner');
var evt = spinner.get("e.toggle");
evt.setParams({ isVisible : true });
evt.fire();
} })

customLookUpHelper.js

 ({
searchHelper : function(component,event,getInputkeyWord) {
var action = component.get("c.fetchObjectList");
action.setParams({
'keyWord': getInputkeyWord,
'objectName' : component.get('v.objectType')
}); action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
var resValue = response.getReturnValue();
if (resValue.length == 0) {
component.set("v.Message", 'No Result Found.');
} else {
component.set("v.Message", 'Search Result As Follows.');
} component.set("v.searchObjList", resValue);
}
});
$A.enqueueAction(action);
}
})

6. Put it in APP It calls

TestCustomLookUpApp.app

 <aura:application extends="force:slds">
<aura:attribute name="selectedUser" type="User"/>
<c:customLookUp selectedRecord="{!v.selectedUser}" objectType="User"/>
<lightning:button onclick="{!c.showInformation}" label="show information"/>
</aura:application>

TestCustomLookUpAppController.js

 ({
showInformation : function(component, event, helper) {
alert(component.get('v.selectedUser').Id);
}
})

Result display : Components can be used directly according to the selectedUser Get the selected User Of Id Etc .

summary : It's just a simple encapsulation function , And only single selection is allowed , For those who are interested in multiple choice, it can be realized . There are not many changes . Please point out any mistakes in the passage , Welcome to leave a message if you don't understand .

salesforce lightning Zero base learning ( Twelve ) Customize Lookup Component implementation of more related articles

  1. salesforce lightning Zero base learning ( 15、 ... and ) One of the common components Get the Picklist( Multilingual )

    This article is for reference :salesforce Zero base learning ( Sixty-two ) obtain sObject The type in is Picklist Of field values( contain record type) We are lightning In the front desk will often encounter access pi ...

  2. salesforce lightning Zero base learning ( Ten ) Aura Js On "three" : $A、Action、Util piece

    The first two chapters respectively introduce Component Class and Event class , This article will talk about $A , Action as well as Util.   One . Action Action Class is usually used for and apex Background interaction , Set parameters , Call the background as well as the knot ...

  3. salesforce lightning Zero base learning ( fourteen ) Toast Shallow in, shallow out

    This article references : https://developer.salesforce.com/docs/component-library/bundle/force:showToast/specification h ...

  4. salesforce lightning Zero base learning ( sixteen ) One of the common components Get field label Information

    Many of our projects are multilingual , Titles in different languages for different countries . We are classic Medium VF page It's very handy , Because the system has been packaged, we can directly in VF obtain label/api name etc. ...

  5. salesforce lightning Zero base learning ( seventeen ) Upload Excel Analyze its content

    This article references : https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader https://github.com/SheetJS/sheetjs ...

  6. salesforce lightning Zero base learning ( Two ) lightning A brief introduction to knowledge ----lightning Event driven model

    Before or after reading this blog , to glance at trailhead Can deepen the impression and understand better :https://trailhead.salesforce.com/modules/lex_dev_lc_basics done cla ...

  7. salesforce lightning Zero base learning ( 13、 ... and ) Customize Lookup Components (Single &amp; Multiple)

    The last article briefly introduced the custom Lookup Radio components , The function is to reference the component Attribute Pass on the relevant sObject Name, Capture user input , So as to realize the function of search . When we do the project , It's possible to get... From multiple tables ...

  8. salesforce lightning Zero base learning ( 7、 ... and ) There are two kinds of custom edit pages when displaying data in a list

    Last one Lightning The content describes LDS, adopt LDS You can easily instantiate the data information of an object . When we need to edit the data displayed in a list , We often use two ways to deal with editing pages :Pop Up Window Pop up modify details to ...

  9. salesforce lightning Zero base learning ( Nine ) Aura Js On the second : Event piece

    In the last introduction Aura Framework in Component Partial methods of the class , This article will introduce Event Common methods . 1. setParam (String key , Object value): Set up events ...

Random recommendation

  1. WWDC 2013 Session note - iOS7 Multitasking in

    This is my WWDC2013 One of a series of notes , For a complete list of notes, please refer to this overview . This article is for personal record only , Also welcome to reprint or use within the scope of the license agreement , But please keep the original link , Thank you for your understanding and cooperation . If you think this website can help you , ...

  2. Serial communication class ,WPF

    Refer to the previous information , Write a own commonly used serial class , There are two ways to send a string type ,char[] and byte[] : There are two ways to receive data char[] and byte[] Two kinds of . Class code : public cl ...

  3. liux I used it zip Unpack the command

    Use description zip File is a common compressed file format ,WinZip.WinRar And other compression software support zip File format , Even java Of jar So is the bag zip Format Of ,Firefox plug-in unit xpi Documents are also zip Format .Linu ...

  4. OpenSSL Major loopholes -Heartbleed Exploit script POC Explain

    OpenSSL Security Advisory [07 Apr 2014] ======================================== TLS heartbeat read ...

  5. logstash Output to elasticsearch Auto build index

    because es single index The amount of data we can handle is limited , Before, it was until 400w data 300G Left and right , The insertion of the whole data will be very slow ( Index reconstruction ) It may even lead to the disconnection of communication between clusters , So we use one every day index To alleviate ...

  6. How to stop sql Inject (pdo piece )

    Use prepared statements and parameterized queries. These are SQL statements that are sent to and par ...

  7. Highway LSTM Learning notes

    Highway LSTM Learning notes zoerywzhou@gmail.com http://www.cnblogs.com/swje/ author :Zhouwan  2016-4-5   Statement 1) The Dee ...

  8. ArrayList Several cases of loop traversal and deletion of elements

    The following code , Want to loop through the elements in the list b, What to do with ? public class ListDemo { public static void main(String[] args) { ArrayList ...

  9. eclipse How to solve the garbled Chinese annotation

    It's usually used for projects UTF-8 Coded ,eclipse The default encoding for is GBK, You're on the menu bar Window in , choose Preferences Options , The first one is General Inside Workspace, After selection, there is a Text file ...

  10. 【 Euler function 】BZOJ4173- mathematics

    [ The main idea of the topic ] [ Ideas ] Basic is popoqqq My master's solution , Add a few comments of your own , Easy to understand Empathy , If n%k+m%k<k Equivalent to 0 =∑([(n+m)/k]-[n/k]-[m/k])×φ(k) … ...