本篇参考:http://sfdcmonkey.com/2017/01/07/custom-lookup-lightning-component/,在参考的demo中进行了简单的改动和优化。
我们在https://www.cnblogs.com/zero-zyq/p/7463016.html 中使用jquery的DataTable做出来类似增强版的Lookup组件效果,通过Name可以搜索出指定的数据,选中以后获取选中的object的名称以及ID信息。此篇主要内容为lightning下使用aura框架的公用Lookup组件的实现。
本篇中的组件主要有以下几个功能:
1. 当输入两位以上字符情况下,从后台数据库检索并且放在搜索框列表中展示;
2. 当选中搜索框列表中某个指定的单元后,选中的单元会以pill的方式展示在输入框中,同时输入框隐藏,列表选择框隐藏;
3. 删除选中的单元以后,输入框变成可用状态。
实现方式如下:
1. 首先将slds的文件夹放在static resource中,demo中的路径为:slds_resource。下载的文件路径为:https://www.lightningdesignsystem.com/downloads/
包打开的结构如下:
2. 创建svg.component,用于显示slds提供的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:用于当搜索出来的列表选中某个指定的单元后,传递给父组件。
<aura:event type="COMPONENT" description=" pass the selected sObject in the parent component">
<aura:attribute name="objectByEvent" type="sObject"/>
</aura:event>
4. customLookUpResult.cmp:用于显示搜索出来的结果的每个单元的展示组件,当选中单元后触发上面的事件。
<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 :主要包括几部分主要内容:
- 根据传递过来的 object 的API Name获取Label动态显示搜索的 object的Label信息;
- 展示搜索按钮,搜索后触发controller的handler来控制后台结果集的展示;
- 搜索时spinner的展示和隐藏;
- 移除选中的单元后,启用输入状态等。
<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. 放在APP 里面调用
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);
}
})
结果展示:通过组件可以直接根据selectedUser获取选中的User的Id等信息。
总结:篇中只是简单的进行封装功能,并且只允许单选,对于多选感兴趣的可以实现。改动的点不是很多。篇中有错误的地方欢迎指出,不懂的欢迎留言。