Ad Code

How to create custom lookup in salesforce lightning component

How to create custom lookup in salesforce

In this post, I am going to show an easy way to create a custom lookup in Salesforce lightning component. Custom lookups play an important role to display different recordset with different criteria and it needs custom filters in SOQL to fetch the records. 

Requirement: Create a sample lightning component with a searchable input text field. When the user starts typing the text, get standard and custom objects based on the search term and display resulting records as list items to the input field, refer image below.


custom lookup in salesforce 1


Steps

Create lightning component: poc

poc.cmp code

<aura:component controller='ObjectController' implements="flexipage:availableForAllPageTypes">
    <aura:attribute name="ObjectList" type="String[]"/>
    <aura:attribute name="fieldList" type="String[]" />
    <aura:attribute name="searchKey" type="String"/>
   
    <div class="slds-size_6-of-12">
        <lightning:input name="ObjectInput"
                         Label="Object"
                         class=""
                         onkeyup="{!c.getObjectList}"
                         value="{!v.searchKey}"
                         placeholder="Search Objects"/>
       
        <!-- list of address display -->
        <aura:if isTrue="{!not(empty(v.ObjectList))}">
            <div class="Address-listbox" role="listbox">
                <ul aura:id="Address-listbox" class="slds-listbox slds-listbox_vertical slds-dropdown slds-dropdown_fluid" role="presentation">
                    <aura:iteration items="{!v.ObjectList}" var="objList">
                        <li role="presentation"
                            onclick="{!c.selectOption}"
                            data-value="{!objList.object_label}"
                            class="slds-listbox__item">
                            <span id="listbox-option-unique-id-01"
                                  class="slds-media slds-listbox__option slds-listbox__option_entity slds-listbox__option_has-meta"
                                  role="option">
                                <span class="slds-media__body slds-m-left_xx-small slds-m-bottom_xx-small">
                                    <div class="slds-col slds-size_4-of-12">
                                        <div class="slds-m-left_medium slds-col ">
                                            <span class="slds-listbox__option-text slds-listbox__option-text_entity"><b>{!objList.object_name}</b></span>
                                        </div>
                                        <div class="slds-col slds-size_1-of-5"></div>
                                    </div>
                                </span>
                            </span>
                        </li>
                    </aura:iteration>
                </ul>
            </div>
        </aura:if>
    </div>
    <aura:if isTrue="{!not(empty(v.fieldList))}">
        <div class="slds-m-top_medium">
            <aura:iteration items="{!v.fieldList}" var="f">
                <div class="slds-m-bottom_x-small">
                    {!f}
                </div>
            </aura:iteration>
        </div>
    </aura:if>
</aura:component>



pocController.js code

({
    getObjectList: function(component, event, helper) {
        component.set("v.fieldList", null);
        var action = component.get("c.getAllObjects");
        var serString = component.get("v.searchKey");
        action.setParams({
            searchString: serString
        });
        action.setCallback(this, function (response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var objectMap = response.getReturnValue();
                //var predictions = response.predictions;
                var objects = [];
                if (response != null ) {
                    for(var key in objectMap){
                        objects.push(
                            {
                                object_name: objectMap[key],
                                object_label: key
                            });
                    }
                }
                component.set("v.ObjectList", objects);
            }
        });
        $A.enqueueAction(action);
    },
   
    selectOption:function(component, event, helper) {
        component.set("v.ObjectList", null);
        var selectedValue = event.currentTarget.dataset.value;
        //alert(selectedValue);
        //var key = component.get("v.searchKey");
        var action = component.get("c.getFieldsByObjectName");
        action.setParams({
            objectName:selectedValue
        });
       
        action.setCallback(this, function (response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var response = response.getReturnValue();
                component.set("v.fieldList", response);
            }
        });
        $A.enqueueAction(action);
    },
})



Create Apex class: ObjectController

public class ObjectController {
    @AuraEnabled
    public static map<string, string> getAllObjects(string searchString){
        searchString = searchString + '%';
        system.debug(searchString);
        map<string, string> objectList = new map<string, string>();
        List<EntityDefinition> objList = [select MasterLabel, QualifiedApiName from EntityDefinition where QualifiedApiName
                                          like:searchString order by MasterLabel asc];
        system.debug(objList.size());
        for(EntityDefinition ent: objList){
            objectList.put(ent.QualifiedApiName, ent.MasterLabel);
        }
        return objectList;
    }
   
    @AuraEnabled
    public static List<string> getFieldsByObjectName(String objectName){
        list<string> fieldList = new  list<string>();
        Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        Map <String, Schema.SObjectField> fieldMap = schemaMap.get(objectName).getDescribe().fields.getMap();
        for(Schema.SObjectField sfield : fieldMap.Values())
        {
            schema.describefieldresult dfield = sfield.getDescribe();
            fieldList.add(dfield.getLabel());
        }
        return fieldList;
    }
}


getAllObjects method in the apex class gives the list of objects


custom lookup in salesforce 2



getFieldsByObjectName method gives a list of fields for a respective object


custom lookup in salesforce 3


Test the new component by adding it to a new lightning app or to any page layout in the lightning app builder. 

Well done! You just created a custom lookup, which is an important feature in the salesforce lightning framework. Explore more on enhancing this lookup. If you see any issues in creating this, put it in the comments section below.


You may like these:



Post a Comment

1 Comments