Icon for the Lightning Components topic

How to create a reusable field search Lightning Component [LWC]

In this tutorial, I will show you how to create a reusable field search Lightning Component using Lightning Web Components. In the GIF below you can see the final result.

How to create a reusable field search Lightning Component

A brief summary of how the field search Lightning Component works:

  • It has two important parts: a search field and a dropdown suggestion list.
  • The data, in this case all the fields of the Account SObject, is fetched from Apex as a list using the Wire Service.
  • With each letter entered in the search field, the Wire Service fetches from Apex a list of all fields where the entered word occurs as a partial word and displays all found fields.
  • After selecting a field, the dropdown list closes and displays the selected field as a lightning-pill.

lwcSearchObjectFields.html

<template>
    <div class="slds-combobox_container">
        <div class={boxClass} aria-expanded="true" aria-haspopup="listbox" role="combobox">
            <div class="slds-combobox__form-element" role="none">
                <template if:true={isValueSelected}>
                    <div class="slds-pill-container">
                        <lightning-pill
                                class="pillSize"
                                label={selectedFieldLabel}
                                onremove={handleRemovePill}
                        >
                        </lightning-pill>
                    </div>
                </template>
                <template if:false={isValueSelected}>
                    <lightning-input
                            class={inputClass}
                            type="search"
                            variant="label-hidden"
                            label=""
                            placeholder={searchPlaceholder}
                            value={searchTerm}
                            onclick={handleClick}
                            onchange={onChange}
                            autocomplete="off"
                    >
                    </lightning-input>
                </template>
            </div>
            <div class="slds-dropdown slds-dropdown_length-with-icon-7 slds-dropdown_fluid" role="listbox">
                <ul class="slds-listbox slds-listbox_vertical" role="presentation">
                    <template for:each={listOfFields} for:item="rec">
                        <li key={rec} data-id={rec.fieldName} data-name={rec.fieldLabel} data-item={rec.fieldType} onclick={onSelect} role="presentation">
                            <span class="slds-lookup__item-action" role="option">
                                <span class="slds-truncate">{rec.fieldLabel}</span>
                            </span>
                        </li>
                    </template>
                </ul>
            </div>
        </div>
    </div>
</template>

lwcSearchObjectFields.js

import {api, LightningElement, wire} from 'lwc';

import getListOfFields from '@salesforce/apex/SfWiki_Handler.getListOfFields';

export default class LwcSearchObjectFields extends LightningElement {

    @api searchPlaceholder = "Search";
    @api isValueSelected;
    @api selectedFieldLabel;
    @api sObjectName;

    listOfFields;
    searchTerm;

    //CSS
    boxClass = 'slds-combobox slds-dropdown-trigger slds-dropdown-trigger_click slds-has-focus';
    inputClass = '';

    @wire(getListOfFields, {sObjectName: '$sObjectName', searchTerm : '$searchTerm'})
    wiredRecords({ error, data }) {
        if (data) {
            let listOfFields = [];
            for(let i = 0; i < data.length; i++) {
                let tempRecord = Object.assign({}, data[i]); //cloning object
                listOfFields.push(tempRecord);
            }
            listOfFields.sort(this.compare);
            this.listOfFields = listOfFields;
        } else if (error) {
            console.log(error);
        }
    }

    handleClick() {
        this.searchTerm = '';
        this.inputClass = 'slds-has-focus';
        this.boxClass = 'slds-combobox slds-dropdown-trigger slds-dropdown-trigger_click slds-has-focus slds-is-open';
    }

    onSelect(event) {
        let selectedFieldApiName = event.currentTarget.dataset.id;
        this.selectedFieldLabel = event.currentTarget.dataset.name;
        let selectedFieldType = event.currentTarget.dataset.item;
        const valueSelectedEvent = new CustomEvent('fieldselected', {
            detail: {
                selectedFieldApiName: selectedFieldApiName,
                selectedFieldType: selectedFieldType,
                selectedFieldLabel: this.selectedFieldLabel,
            }});
        this.dispatchEvent(valueSelectedEvent);
        this.isValueSelected = true;
        this.boxClass = 'slds-combobox slds-dropdown-trigger slds-dropdown-trigger_click slds-has-focus';
    }

    handleRemovePill() {
        this.isValueSelected = false;
    }

    onChange(event) {
        this.searchTerm = event.target.value;
    }

    /**
     * This function compares two fields (for sorting purposes) with each other
     */
    compare(a, b) {
        // Use toUpperCase() to ignore character casing
        const fieldLabelA = a.fieldLabel.toUpperCase();
        const fieldLabelB = b.fieldLabel.toUpperCase();

        let comparison = 0;
        if (fieldLabelA > fieldLabelB) {
            comparison = 1;
        } else if (fieldLabelA < fieldLabelB) {
            comparison = -1;
        }
        return comparison;
    }

}

SfWiki_Handler.cls

public without sharing class SfWiki_Handler {

    @AuraEnabled(Cacheable=true)
    public static List<Fields> getListOfFields(String sObjectName, String searchTerm) {
        List<Fields> listOfFields = new List<Fields>();

        Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        Map<String, Schema.SObjectField> fieldMap = schemaMap.get(sObjectName).getDescribe().fields.getMap();

        for(String fieldName : fieldMap.keySet()) {
            //We don't want to search for fields with these data-types: ADDRESS, REFERENCE, ID & URL
            if(String.valueOf(fieldMap.get(fieldName).getDescribe().getType()) != 'ADDRESS'
                    && String.valueOf(fieldMap.get(fieldName).getDescribe().getType()) != 'REFERENCE'
                    && String.valueOf(fieldMap.get(fieldName).getDescribe().getType()) != 'ID'
                    && String.valueOf(fieldMap.get(fieldName).getDescribe().getType()) != 'URL') {
                if(String.valueOf(fieldMap.get(fieldName).getDescribe().getLabel().toLowerCase()).contains(searchTerm.toLowerCase())) {
                    Fields newFieldProperties = new Fields();
                    newFieldProperties.fieldLabel = fieldMap.get(fieldName).getDescribe().getLabel();
                    newFieldProperties.fieldName = fieldMap.get(fieldName).getDescribe().getName();
                    newFieldProperties.fieldType = String.valueOf(fieldMap.get(fieldName).getDescribe().getType());
                    listOfFields.add(newFieldProperties);
                }
            }

        }

        return listOfFields;
    }

    public class Fields {
        @AuraEnabled
        public String fieldLabel { get; set; }
        @AuraEnabled
        public String fieldName { get; set; }
        @AuraEnabled
        public String fieldType { get; set; }
    }

}

Example how to use

lwcExampleComponent.html

<template>

    <div class="slds-card" style="font-family: 'Open Sans', sans-serif">

        <!-- Header -->
        <header class="slds-card__header slds-media slds-media_center">
            <div class="slds-media__figure">
                <lightning-icon icon-name="standard:custom_notification" size="small"></lightning-icon>
            </div>
            <div class="slds-media__body slds-card__header-title slds-text-title_bold" style="font-size: 14px">
                Example Component
            </div>
        </header>

        <!-- Body -->
        <div class="slds-p-around_small">
            <div class="slds-text-align_center slds-container_center" style="font-size: 15px;">
                <div class="slds-size_2-of-3 slds-align_absolute-center slds-p-bottom_small">
                    <c-lwc-search-object-fields
                            s-object-name="Account"
                            search-placeholder="Search Account field"
                            onfieldselected={handleFieldSelection}
                    >
                    </c-lwc-search-object-fields>
                </div>
                <p>Field-Label: <span style="font-weight: bold">{selectedFieldLabel}</span></p>
                <p>Field-API-Name: <span style="font-weight: bold">{selectedFieldApiName}</span></p>
                <p>Field-Datatype: <span style="font-weight: bold">{selectedFieldType}</span></p>
                <p class="slds-p-top_small">Hope you like this tutorial</p>
                <p style="font-weight: bold; color: red">Sf <span style="font-weight: bold; color: black">Wiki</span></p>
            </div>
        </div>

    </div>

</template>

lwcExampleComponent.js

import {LightningElement} from 'lwc';

export default class LwcExampleComponent extends LightningElement {

    selectedFieldLabel;
    selectedFieldApiName;
    selectedFieldType;

    handleFieldSelection(event) {
        this.selectedFieldLabel = event.detail.selectedFieldLabel;
        this.selectedFieldApiName = event.detail.selectedFieldApiName;
        this.selectedFieldType = event.detail.selectedFieldType;
    }

}

That’s it!

I hope you have enjoyed learning “How to create a reusable field search Lightning Component [LWC]”. Please share your thoughts in the comments below. If you find value in this type of post, please subscribe because we have tons of tutorials in progress to be posted!

If you prefer to see the result with Lightning Aura Components, here’s the link to it: How to create a reusable field search Lightning Component [Aura].

How to create a reusable field search Lightning Component using Lightning Aura Components

How to create a reusable field search Lightning Component [Aura]

In this tutorial, I will show you how to create a reusable field search Lightning Component in Lightning Aura Components.

How to create a reusable field search Lightning Component using Lightning Web Components

How to create a reusable field search Lightning Component [LWC]

In this tutorial, I will show you how to create a reusable field search Lightning Component in Lightning Web Components.

How to create a reusable Lookup Lightning Component

How to create a reusable Lookup Lightning Component [Aura]

In this tutorial, I will show you how to create a reusable Lookup Lightning Component in Lightning Aura Components.

How to create a reusable Lookup Lightning Component

How to create a reusable Lookup Lightning Component [LWC]

In this tutorial, I will show you how to create a reusable Lookup Lightning Component in Lightning Web Components.

How to remove Lightning App Page Header

How to remove Lightning App Page Header [Aura]

In this tutorial, I will show you how to remove Lightning App Page Header in Lightning Aura Components.

Leave a comment!

0 0 votes
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments
Hamid Abassi

Hamid Abassi

SfWiki Founder

I am a Salesforce Developer from Hamburg who wants to help the Salesforce Community around the world with my tutorials. Feel free to explore my website and hopefully learn something new.