A blog about Salesforce CRM Configuration and development

Wednesday, 16 January 2019

Super fast records searching in the lightning component.

Lightning component client-side searching/filter.
Hello Everyone,

We generally make the server call to search the records in the table on the lighting component/VF page. As we know that the concept of Lightning Component development is based on reducing the server calls, so I have demonstrated client-side record filter/search in this lightning component. 


Component
 <aura:component controller="ListComponentCntrl" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >  
   <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>  
   <aura:attribute name="data" type="Contact[]" />  
   <aura:attribute name="UnfilteredData" type="Contact[]" />  
   <aura:attribute name="filter" type="String" />  
   <aura:handler name="change" value="{!v.filter}" action="{!c.doFilter}" />  
   <div class="slds-page-header">My Contacts</div>  
   <lightning:input name="x" value="{!v.filter}" label="Filter" placeholder="Search Contact by "/>  
   <table class="slds-table slds-table--bordered">  
     <thead>  
       <tr>  
         <th>Id</th>  
         <th>Name</th>  
         <th>Email</th>  
       </tr>  
     </thead>  
     <tbody>  
       <aura:iteration items="{!v.data}" var="row" indexVar="rowIndex">  
         <tr>  
           <td>{!row.Id}</td>  
           <td>{!row.Name}</td>  
           <td>{!row.Email}</td>  
         </tr>  
       </aura:iteration>  
     </tbody>  
   </table>   
 </aura:component>  
JS Controller
 ({  
   doInit :function(component,event,helper){  
     // Apex method definition  
     var action = component.get("c.loadData");  
     // callbak function  
     action.setCallback(this,function(response){  
       //get state  
       var state = response.getState();  
       // check if state is 'SUCCESS'  
       if(state == 'SUCCESS'){  
         var result = response.getReturnValue();  
         //set value to "UnfilteredData" attaribute   
         component.set("v.UnfilteredData",result);  
         console.log(result);  
         // set value to "data" attaribute  
         component.set("v.data",result);  
       }else{  
         console.log('something bad happend! ');  
       }  
     });  
     // put the action into queue for server call.  
     $A.enqueueAction(action);  
   },  
   doFilter: function(component, event, helper) {  
     //calling helper  
     helper.FilterRecords(component);  
   }  
 })  
JS Controller Helper
 ({  
   FilterRecords: function(component) {  
     //data showing in table  
     var data = component.get("v.data");  
     // all data featched from apex when component loaded  
     var allData = component.get("v.UnfilteredData");  
     //Search tems  
     var searchKey = component.get("v.filter");  
     // check is data is not undefined and its lenght is greater than 0  
     if(data!=undefined || data.length>0){  
       // filter method create a new array tha pass the test (provided as function)  
       var filtereddata = allData.filter(word => (!searchKey) || word.Name.toLowerCase().indexOf(searchKey.toLowerCase()) > -1);  
       console.log('** '+filtereddata);  
     }  
     // set new filtered array value to data showing in the table.  
     component.set("v.data", filtereddata);  
     // check if searchKey is blank  
     if(searchKey==''){  
       // set unfiltered data to data in the table.  
       component.set("v.data",component.get("v.UnfilteredData"));  
     }  
   }  
 })  
Apex Controller
 public class ListComponentCntrl {  
   @AuraEnabled  
   public static List<Contact> loadData(){  
     List<Contact> conList = [select Id,Name,Email from Contact order by Name asc];  
     return conList;  
   }  
 }  


Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Hope this blog post helps many.

Happy Coding... :)
Share:

9 comments:

  1. hi query how does doFilter gets called

    ReplyDelete
    Replies
    1. Hi PHOENIX1390,

      <aura:handler name="change" value="{!v.filter}" action="{!c.doFilter}" >

      <aura:handler> handle the change event on filter (attribute) and call the doFilter function.

      Delete
  2. thanks Arun experimented it great article

    ReplyDelete
  3. Hi Arun ,
    I'm getting an error "Cannot read property 'toLowercase' of undefined."
    Please advise


    Thanks And Regards
    Nikhil




    ReplyDelete
    Replies
    1. Hello Nikhil,

      The 'allData' variable may be 'undefined' in your case. Can you post your code here? OR you can check by debugging the code (console.log()).

      Thanks
      Arun Kumar

      Delete
  4. Hi arun,
    Here's my code for that function
    FilterRecords: function(component) {
    //data showing in table
    var currentList = component.get("v.currentList");
    // all data featched from apex when component loaded
    var action = component.get("c.getAllregistrations");
    action.setCallback(this, function(response){
    var name = response.getState();
    var records = response.getReturnValue();
    if (name === "SUCCESS") {
    component.set("v.UnfilteredData", records);
    }
    })
    var allData = component.get("v.UnfilteredData");
    //Search tems
    var searchKey = component.get("v.filter");
    // check is data is not undefined and its lenght is greater than 0
    if(currentList!=undefined || currentList.length>0){
    // filter method create a new array tha pass the test (provided as function)
    var filtereddata = currentList.filter(word => (!searchKey) || word.LinkedEntityName.toLowerCase().indexOf(searchKey.toLowerCase()) > -1);
    console.log('** '+filtereddata);
    }
    // set new filtered array value to data showing in the table.
    component.set("v.currentList", filtereddata);
    // check if searchKey is blank
    if(searchKey==''){
    // set unfiltered data to data in the table.
    component.set("v.currentList",component.get("v.currentList"));
    }
    }

    ReplyDelete
  5. Can we use this method for Multiple fields? If yes, how?

    ReplyDelete
  6. Can we use this method for Multiple fields in a table of records?and how to put that filter?

    ReplyDelete

Trailhead Profile


Follow by Email

Total Pageviews

Followers

Popular Posts

Powered by Blogger.

Contact form

Name

Email *

Message *