Implement Searching In Lightning Data Table in LWC Component.

Posted on April 30, 2022 Post Thumbnail

Hi Trailblazers,

Welcome back to heySalesforce.

In this blog post, I'm going to create a Lightning Web Component, In this component, We can search a record in Lightning DataTable.

Before reading this blog post, Have a look at following demo.

https://miricommunity01102020-developer-edition.ap15.force.com/mapmarkerlwc/s/searchindatatable

Picture of component.

What you'll Learn from Blog Post?

1. DataTable in LWC Component with Account Data.

2. Implement Searching in JS Controller.

3. Make your component public for External Users.

Walkthrow.

1. After querying data, We save it to an Array.

2. After that, We'll copy that array to new array.

3. And In new array We perform Searching using following code.

let searchKey = event.detail.value.toLowerCase();
        let searchedTempAccounts = [];
        if (event.detail.value.length > 1) {
            for (const account of this.mainAllAccounts) {
                if (account.Name.toLowerCase().includes(searchKey))
                    searchedTempAccounts.push(account);
            }
            this.allAccounts = searchedTempAccounts;
        }
        if (event.detail.value.length == 0)
            this.allAccounts = this.mainAllAccounts;
    }

Let's Start :)

First create following class for querying data.

Apex Class: SearchInDataTableCtrl

public without sharing class SearchInDataTableCtrl {
    @AuraEnabled
    public static list<Account> getAllAccounts(){
        return [SELECT Id, Name, Phone FROM Account WHERE createddate < 2020-01-01T01:02:03Z];
    }
}

Now Create a LWC Component.

SearchInDataTable.html

<template>
    <lightning-card>
        <h3 slot="title">
            <lightning-icon class="slds-m-right_x-small" icon-name="standard:account" size="small"></lightning-icon>
            Search Accounts
        </h3>
        <div class="slds-p-horizontal_small">
            <lightning-input name="enter-search" label="" type="search" placeholder="Search Account..."
                onchange={searchHandler}></lightning-input>
        </div>
        <div class="slds-m-top_x-small slds-box outerDesign">
            <div style={tableHeight}>
                <lightning-datatable key-field="id" data={allAccounts}
                    columns={columns}>
                </lightning-datatable>
            </div>
        </div>
    </lightning-card>
</template>

SearchInDataTable.js

import { LightningElement, track } from 'lwc';
import getAllAccounts from '@salesforce/apex/SearchInDataTableCtrl.getAllAccounts';
const columns = [
    { label: 'Name', fieldName: 'Name' },
    { label: 'Phone', fieldName: 'Phone', type: 'phone' },
];
export default class SearchInDataTable extends LightningElement {
    @track allAccounts = [];
    @track mainAllAccounts = [];
    columns = columns;
    connectedCallback() {
        getAllAccounts()
            .then(response => {
                this.allAccounts = response;
                this.mainAllAccounts = response;
                if (response.length > 5) {
                    this.tableHeight = 'height: 200px';
                }
            })
    }
    searchHandler(event) {
        let searchKey = event.detail.value.toLowerCase();
        let searchedTempAccounts = [];
        if (event.detail.value.length > 1) {
            for (const account of this.mainAllAccounts) {
                if (account.Name.toLowerCase().includes(searchKey))
                    searchedTempAccounts.push(account);
            }
            this.allAccounts = searchedTempAccounts;
        }
        if (event.detail.value.length == 0)
            this.allAccounts = this.mainAllAccounts;
    }
}

SearchInDataTable.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>54.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>Search Accounts in DataTable</masterLabel>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
        <target>lightningCommunity__Page</target>
        <target>lightning__FlowScreen</target>
    </targets>
</LightningComponentBundle>

After creating both Apex Class & LWC Component.

Final Component: Search Accounts in DataTable

https://miricommunity01102020-developer-edition.ap15.force.com/mapmarkerlwc/s/searchindatatable

Search Accounts in DataTable

You can Access it publicly after clicking above links.

If you want to learn how to make components Public in Salesforce, Please have a look at following Blog Post.

Make Your Lightning Components Publicly Accessible.

Note: This is just for Study Purposes And Above code may not follow best practices.

If you have any question Ask Me

Thanks for Reading :)

Write a comment for suggestions and hit the heart icon.


818
1

Tags: #salesforce #lwc #lightningComponent

Comments

  • Vivek Bidla Avatar
    Vivek Bidla - 2 months ago
    This is literally what I was looking for. Thanks Asif.

Your message is required.

Get notified of new posts