Filter Search in LWC Lightning Datatable

by Rijwan Mohmmed
filter-search-in-lwc-lightning-datatable-techdicer

Hello friends, Today we are going to discuss Filter Search in LWC Lightning Datatable Salesforce. Datatable is a table where we show the data in tabular form. When there are large data we use a search filter. Based on any column we enter the text in the search box the relevant record will display.

Also check this: LWC Datatable CSS Styling

filter-search-in-lwc-lightning-datatable-output-techdicer
filter-searchs-in-lwc-lightning-datatable-output-techdicer

Key Highlights :

  1. Filter the data by search box.
  2. Search in all columns.
  3. Show extensive data in the table
  4. Display data based on the data type by defining the columns object.
  5. Tables can be populated during initialization using the datacolumns, and key-field attributes.

Process & Code :

DataController.cls :

public with sharing class DataController {
    
    @AuraEnabled (cacheable=true)
    public static List<Account> retrieveAccounts(){
        return [SELECT Id, Name, Type, BillingCountry, Industry, Email__c
                FROM Account
                LIMIT 2000];
    }
}

lWCFilterSearchDatatable.html :

<template>
	<lightning-card title="Accounts" icon-name="standard:account">
		<div class="slds-m-around_medium">
			<lightning-layout multiple-rows>
                <lightning-layout-item size="6" padding="around-small"></lightning-layout-item>
				<lightning-layout-item size="6" padding="around-small">
					<lightning-input type="search" label="Search Account" onchange={handleSearch}></lightning-input>
				</lightning-layout-item>
			</lightning-layout>
			<template if:true={data}>
				<lightning-datatable key-field="Id" data={data} columns={columns} hide-checkbox-column="true"
					show-row-number-column="true" onrowaction={handleRowAction}>
				</lightning-datatable>
			</template>
			<template if:true={error}>
				{error}>
			</template>
		</div>
	</lightning-card>
</template>

lWCFilterSearchDatatable.js :

import { LightningElement, wire, track } from 'lwc';
import retrieveAccounts from '@salesforce/apex/DataController.retrieveAccounts';

const columns = [
    { label: 'Name', fieldName: 'Name' },
    { label: 'Type', fieldName: 'Type' },
    { label: 'Email', fieldName: 'Email__c', type: 'email' },
    { label: 'BillingCountry', fieldName: 'BillingCountry' },
];

export default class LWCFilterSearchDatatable extends LightningElement {
    @track data;
    @track error;
    @track columns = columns;
    @track searchString;
    @track initialRecords;

    @wire(retrieveAccounts)
    wiredAccount({ error, data }) {
        if (data) {
            console.log(data);
            this.data = data;
            this.initialRecords = data;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.data = undefined;
        }
    }

    handleSearch(event) {
        const searchKey = event.target.value.toLowerCase();

        if (searchKey) {
            this.data = this.initialRecords;

            if (this.data) {
                let searchRecords = [];

                for (let record of this.data) {
                    let valuesArray = Object.values(record);

                    for (let val of valuesArray) {
                        console.log('val is ' + val);
                        let strVal = String(val);

                        if (strVal) {

                            if (strVal.toLowerCase().includes(searchKey)) {
                                searchRecords.push(record);
                                break;
                            }
                        }
                    }
                }

                console.log('Matched Accounts are ' + JSON.stringify(searchRecords));
                this.data = searchRecords;
            }
        } else {
            this.data = this.initialRecords;
        }
    }
}

lWCFilterSearchDatatable.js-meta.xml :

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
	<apiVersion>54.0</apiVersion>
	<isExposed>true</isExposed>
	<targets>
		<target>lightning__HomePage</target>
	</targets>
</LightningComponentBundle>

Output :

filter-search-in-lwc-lightning-datatable-output-techdicer
filter-search-in-lwc-lightning-datatable-output-techdicer

Reference :

  1. LWC Datatable
What’s your Reaction?
+1
0
+1
8
+1
2
+1
1
+1
3
+1
1

You may also like

16 comments

Amo April 24, 2023 - 5:16 am

Hello, i Have a question,what if the ‘key words’ search and record volume is 70K,also want to search in all column

Reply
Rijwan Mohmmed April 27, 2023 - 12:51 pm

How are you fetching the 70k records in lwc datatable

Reply
Ivan S July 2, 2023 - 10:26 am

From my experience, the js search can be working quite fast, rendering of 1000+ records by datatable can take a while though, which might be a limiting factor

Reply
Viqar August 24, 2023 - 10:12 am

very nice Rizwan Bhai your code is simple and easy to understand.

Reply
Rijwan Mohmmed August 24, 2023 - 10:42 am

Thanks @Viqar

Reply
Sree November 6, 2023 - 12:35 pm

In this we are able to search the all the columns and how can we write to search only one column in the table

Reply
Rijwan Mohmmed November 6, 2023 - 1:46 pm

This one for all columns search but you can also do only for 1 column in handle search method

Reply
Daniel November 14, 2023 - 4:23 pm

Hi Rijwan, I have a question, how can I display related fields such as contact

Reply
Rijwan Mohmmed November 15, 2023 - 4:03 am

Hi @Daniel, you mean lookup fields

Reply
Daniel November 17, 2023 - 5:23 pm

right

Reply
Arshiya February 6, 2024 - 5:02 am

Hi Rijwan how can i display lookup fields ? could you please help me

Reply
Arshiya February 7, 2024 - 1:08 pm

Hello Rijwan in data table for a field i dont want field id i want field value how can i add these ?

Reply
Rijwan Mohmmed February 8, 2024 - 10:27 am

Yes you can add. But it should be unique

Reply
Aishwarya March 27, 2024 - 7:26 am

How do you search in only one or two columns and not all columns in javascript?

Reply
Rijwan Mohmmed March 27, 2024 - 8:46 am

Hi Aishwarya, on line number 41 in JS file you can specified column name.

Reply

Leave a Comment