Client Side Search in Lightning Data Table in Lightning Component Salesforce

In this article I will implement the Client Side Search functionality in Lightning Data Table in a Custom Lightning Component.

Client Side Search allows user to search the data from the page itself. You don't have to query records each time, because using client side search we can use the on page database. #Salesforce #LightningComponent #DataTable

Check the code below

Component
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<aura:component controller="LightningDTCTRL" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <aura:attribute name="recordList" type="List"/>
    <aura:attribute name="allData" type="List" />
    <aura:attribute name="columns" type="List"/>
    <aura:attribute name="sortedBy" type="String" default="Name"/>
 <aura:attribute name="sortedDirection" type="string" default="asc" />
    <aura:handler name="init" action="{!c.doInit}" value="{!this}" />
    <span>
    	<lightning:input type="search" lable="Search" placeholder="Search from Accounts" aura:id="SearchBox"
                         onchange="{!c.searchTable}" />
    </span>
    <lightning:layout multipleRows="true" horizontalAlign="center">
            <lightning:layoutItem padding="around-small" size="12">
                <lightning:datatable keyField="id" data="{! v.recordList}"
                                     columns="{! v.columns}"
                                     hideCheckboxColumn="true"
                                     onsort="{!c.updateSorting}"
                                     sortedBy="{!v.sortedBy}"
                                     sortedDirection="{!v.sortedDirection}"  />
            </lightning:layoutItem>
    </lightning:layout>
</aura:component>

Controller Javascript
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
({
    doInit : function(component, event, helper) {
        component.set('v.columns', [
            {label: 'Id', fieldName:'Id',sortable:true,type:'text', initialWidth: 300},
            {label: 'Name', fieldName:'Name',sortable:true,type:'text', initialWidth: 400},
            {label: 'Phone', fieldName:'Phone',sortable:true,type:'text', initialWidth: 300},
            {label: 'Created Date', fieldName:'CreatedDate',sortable:true,type:'text', initialWidth: 400}
        ]);
        helper.getAccounts(component, helper);
    },
    updateSorting: function (cmp, event, helper) {
        var fieldName = event.getParam('fieldName');
        var sortDirection = event.getParam('sortDirection');
        cmp.set("v.sortedBy", fieldName);
        cmp.set("v.sortedDirection", sortDirection);
        helper.sortData(cmp, fieldName, sortDirection);
    },
    searchTable: function (cmp, event, helper) {
        var allRecords = cmp.get("v.allData");
        var searchFilter = event.getSource().get("v.value").toUpperCase();
        var tempArray =[];
        var i;
        for(i=0; i<allRecords.length; i++){
            if((allRecords[i].Name && allRecords[i].Name.toUpperCase().indexOf(searchFilter) != -1) || 
               (allRecords[i].Phone && allRecords[i].Phone.toUpperCase().indexOf(searchFilter) != -1)){
                tempArray.push(allRecords[i]);
            }
        }
        cmp.set("v.recordList",tempArray);
    }
    
})

Helper
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
({
    getAccounts : function(component, helper) {
        var action = component.get("c.getAccountList");
        action.setCallback(this, function(response) {
            var state = response.getState();
            var data;
            if(state === 'SUCCESS'){
                var result = response.getReturnValue();
                component.set("v.recordList", result);
                component.set("v.allData", result);
            }
        });
        $A.enqueueAction(action);
    },
    sortData: function (cmp, fieldName, sortDirection) {
        var fname = fieldName;
        var data = cmp.get("v.recordList");
        var reverse = sortDirection !== 'asc';
        data.sort(this.sortBy(fieldName, reverse))
        cmp.set("v.recordList", data);
    },
    sortBy: function (field, reverse) {
        var key = function(x) {return x[field]};
        reverse = !reverse ? 1 : -1;
        return function (a, b) {
            return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
        }
    }
})

Controller Apex
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public class LightningDTCTRL {
    @AuraEnabled
    public static list<Account> getAccountList(){
        List<Account> accList= [Select Id, Name, Phone, CreatedDate From Account Order By CreatedDate];
        if(accList != null && accList.size()>0){
            return accList;
        }
        else{return null;}
    }
}

Checkout below video for output & complete tutorial :


If you have any question please leave a comment below.
If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Keep Coding 

Post a Comment

0 Comments