Lightning Web Component Datatable example with sorting and search functionality.

Many people are familiar with lightning datatable component and how to use it in Aura Component. In this article I want to show example how to use lightning component in Lightning Web Component and build simple search by name and column sorting.

First we need to create an apex class.

You can create it either in Salesforce UI or Developer Console or do it in Visual Studio Code with SFDX command:

sfdx force:apex:class:create --classname GetAccounts --template DefaultApexClass --outputdir force-app\main\default\classes

Code for Apex class:

Second we will need to create Lightning Web Component budle.

sfdx force:lightning:component:create --type lwc -n LightningDatatableExample -d force-app/main/default/lwc

Code for html component:

JS controller:

To make sure component is visible in Lightning App Builder you need to add targets and change isExposed to true in LightningDatatableExample.js-meta.xml file:

Lightning component table using Lightning Datatable with sorting and pagination.

I recently worked on the project where I needed to create table with pagination, sorting and be able to select page size.

I tried to find a good working example online and could find example where it will work with unlimited number of pages. I saw examples that used LIMIT in the query, which mean not all the records will be shown in the table.

I decided to write a component that will work with any number of records and will use StandardSetController and it’s methods like next(), previous() etc.

LightningTable.cmp

LightningTableController.js

LightningTableHelper.js

LightningTableController.apxc

 public class LightningTableController {
    private static ApexPages.StandardSetController ssc;
    private static String query = 'SELECT Id, Name, FirstName, LastName, Email, MobilePhone FROM Contact';
    
    @AuraEnabled
    public static ResultWrapper getData( Integer pageSize, Integer pageNumber, String sortBy, String sortOrder ){
        
        if( sortby != NULL && sortOrder != NULL  ){
            query += ' ORDER BY '+ sortby+' '+ sortOrder+' NULLS LAST';
        }
       
        ssc = new ApexPages.StandardSetController( Database.getQueryLocator( query ) );
        //set page size
        ssc.setpagesize(pageSize);
        //set page number 
        ssc.setPageNumber( pageNumber );
        return new ResultWrapper( (List)ssc.getRecords(), ssc.getResultSize());
    } 
    
    public class ResultWrapper {
        
        @AuraEnabled
        public List result {get;set;}
        @AuraEnabled
        public Integer totalNumberOfRecords {get;set;}
        
        public ResultWrapper( List result, Integer totalNumberOfRecords) {
            this.result = result;
            this.totalNumberOfRecords = totalNumberOfRecords;
        }
    }
}

}