Wednesday, 12 August 2020

Lightning Datatable Sorting in Lightning Web Components

Last time we talk about Lightning Datatable in Lightning Web Components (LWC). In this post we will talk about lightning datatable example with sorting in lightning web components. We can achieve the column sorting with the help of onsort attribute in datatable.

Lightning-datatable

Lightning datatable provides an onsort attribute which allow us to implement the sorting in lightning datatable. To enable the sorting on row you need to set sortable to true for the column and set sorted-By to match the fieldName attribute on the column. 


Use onsort event handler to update the table with the new column index and sort direction. The sort event returns the following parameter.
  1. fieldName : The fieldName that controls the sorting.
  2. sortDirection : The sorting direction. Valid options include 'asc' and 'desc'.

We can implement the sorting in LWC with following ways :-
  1. sorting locally 
  2. via apex call.

Local Sorting


We mostly implement this type of sorting when we know data elements in lightning datatable is small and limited

  1. Create Apex Class : To select certain contacts using SOQL, use an Apex method. Check this post to learn about how to Call Apex Methods in LWC.
    LWCDataTableSortingExample
    public with sharing class LWCDataTableSortingExample {
        @AuraEnabled(Cacheable=true)
        public static List <Contact> getContacts() {
            List<Contact> contList = [ SELECT Id, FirstName, LastName, Phone, Email
                                       FROM Contact
                                       LIMIT 10 ];
            return contList;
        }   
    }
  2. Create Lightning web component : Create one Lightning web component in your developer org or sandbox.
    dataTableSortingLWC.html
    <template>
        <lightning-card title="Data Sorting in Lightning Datatable in LWC" icon-name="standard:contact" >
            <br/>
            <div style="width: auto;">
                <template if:true={data}>
                    <lightning-datatable data={data}
                                         columns={columns}
                                         key-field="id"
                                         sorted-by={sortBy}
                                         sorted-direction={sortDirection}
                                         onsort={doSorting}

                                         hide-checkbox-column="true"></lightning-datatable>
                </template>
            </div>
        </lightning-card>
    </template>
    • In lightning datatable use sorted-by and sorted-direction attribute to define the direction and sorted column.
    • use onsort event to call javascript function to sort your local data.

    dataTableSortingLWC.js
    import {LightningElement, wire, track} from 'lwc';
    import getContacts from '@salesforce/apex/LWCDataTableSortingExample.getContacts';

    // datatable columns with row actions. Set sortable = true
    const columns = [ { label: 'FirstName', fieldName: 'FirstName', sortable: "true"},
                      { label: 'LastName', fieldName: 'LastName', sortable: "true"},
                      { label: 'Phone', fieldName: 'Phone', type: 'phone', sortable: "true"},
                      { label: 'Email', fieldName: 'Email', type: 'email', sortable: "true" },];

    export default class DataTableSortingLWC extends LightningElement {
        @track data;
        @track columns = columns;
        @track sortBy;
        @track sortDirection;
     
        @wire(getContacts)
        contacts(result) {
            if (result.data) {
                this.data = result.data;
                this.error = undefined;
            } else if (result.error) {
                this.error = result.error;
                this.data = undefined;
            }
        }

        doSorting(event) {
            this.sortBy = event.detail.fieldName;
            this.sortDirection = event.detail.sortDirection;
            this.sortData(this.sortBy, this.sortDirection);
        }

        sortData(fieldname, direction) {
            let parseData = JSON.parse(JSON.stringify(this.data));
            // Return the value stored in the field
            let keyValue = (a) => {
                return a[fieldname];
            };
            // cheking reverse direction
            let isReverse = direction === 'asc' ? 1: -1;
            // sorting data
            parseData.sort((x, y) => {
                x = keyValue(x) ? keyValue(x) : ''; // handling null values
                y = keyValue(y) ? keyValue(y) : '';
                // sorting values based on direction
                return isReverse * ((x > y) - (y > x));
            });
            this.data = parseData;
        }  
      
    }
    •  On which column you want to enable the sorting use sortable: "true"
    • Call your javaScript sorting method from onSorting event.
    dataTableSortingLWC.js-meta.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="dataTableSortingLWC">
        <apiVersion>46.0</apiVersion>
        <isExposed>true</isExposed>
        <targets>
            <target>lightning__AppPage</target>
            <target>lightning__RecordPage</target>
            <target>lightning__HomePage</target>
        </targets>
    </LightningComponentBundle>
        

Sorting by Apex Call


We also have another way of data sorting with Apex class.

  1. Create Apex Class : Update your apex method and include sord column and sort order.

    public with sharing class LWCDataTableSortingExample {
        @AuraEnabled(Cacheable=true)
        public static List <Contact> getContacts(String field, String sortOrder) {
            String query;
            query  = 'SELECT Id, FirstName, LastName, Phone, Email FROM Contact';
            if(field != null && sortOrder !=null){
                query += ' ORDER BY '+field+' '+sortOrder;
            }

            return Database.query(query);
        }
    }
  2. Create Lightning web components :- No change required in html file.

    <template>
        <lightning-card title="Data Sorting in Lightning Datatable in LWC" icon-name="standard:contact" >
            <br/>
            <div style="width: auto;">
                <template if:true={data}>
                    <lightning-datatable data={data}
                                         columns={columns}
                                         key-field="id"
                                         sorted-by={sortBy}
                                         sorted-direction={sortDirection}
                                         onsort={doSorting}
                                         hide-checkbox-column="true"></lightning-datatable>
                </template>
            </div>
        </lightning-card>
    </template>


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

    // datatable columns with row actions. Set sortable = true
    const columns = [ { label: 'FirstName', fieldName: 'FirstName', sortable: "true"},
                      { label: 'LastName', fieldName: 'LastName', sortable: "true"},
                      { label: 'Phone', fieldName: 'Phone', type: 'phone', sortable: "true"},
                      { label: 'Email', fieldName: 'Email', type: 'email', sortable: "true" },];

    export default class DataTableSortingLWC extends LightningElement {
        @track data;
        @track columns = columns;
        @track sortBy='FirstName';
        @track sortDirection='asc';
     
        // retrieving the data using wire service
        @wire(getContacts,{field : '$sortBy',sortOrder : '$sortDirection'})
        contacts(result) {
            if (result.data) {
                this.data = result.data;
                this.error = undefined;
            } else if (result.error) {
                this.error = result.error;
                this.data = undefined;
            }
        }
        doSorting(event) {
            // calling sortdata function to sort the data based on direction and selected field
            this.sortBy = event.detail.fieldName;
            this.sortDirection = event.detail.sortDirection;
        }
    }
    •  Retrieving the data using wire service. Wire will automatically call your apex class when sort field or direction will change
    • Call onSorting method when sort event will fire. 

If you want to load to many record on one single page then use Lazy loading in dataTable.

9 comments:

  1. Thank you for sharing this valuable information.

    Apparrant is the leading UX UI Design agency having experienced designers and developers working throughout the year on important and life changing products. We have been awarded as top UI UX Design agency in India by multiple agencies. If you are looking for best UX Design Agency in Noida, UI UX Design Agency in Faridabad, and UX UI Design Company in Delhi then Apparrant is best for you.

    ReplyDelete
  2. Nice Information. I really liked it and admire you for posting it on the internet for the benefit of a larger Audience.

    If you are looking for best App design and development company in Noida, Delhi NCR, Gurgaon, Faridabad and India then Apparrant is Awesome. We have been known as leading Mobile and web application development company in Noida, India. Work of Apparrant can be checked on our website along with the processes we follow in to the web or App design and technologies we use at Apparrant.

    ReplyDelete
  3. Thanks for sharing this information.
    Yes Done is the best online site for on demand home services, professional service providers in Jaipur, Rajasthan. We are providing top services like carpenter, cleaning, TV, best pest control services in Jaipur, ro repair service in Jaipur, ac repair service in Jaipur online by Yes Done is there for services at your doorstep in Jaipur, Rajasthan. For more service visit our website. For more services visit our website.

    ReplyDelete
  4. It's a great blog, shares a piece of good information.

    GIEC Global is the leading education and migration consultants in Australia. We are top Education consultants in Melbourne, Sydney, Perth, Brisbane, Adelaide and Australia. We are best education consultants for Canada in Australia. We also helps people in studying in USA and have been awarded as education consultants for USA in Melbourne and education consultant for UK in Australia.

    ReplyDelete
  5. The awesome blog shares good information with everyone. I will bookmark it in the future.

    France Education Consultants in Australia is GIEC Global. We are top Education consultants for Norway in Melbourne, Sydney, Perth, Brisbane, Adelaide and Australia. We are best education consultants for Netherlands in Australia. We also helps people in studying in Ireland and have been awarded as education consultants for Ireland in Melbourne and education consultant for Finland in Australia.

    ReplyDelete
  6. Nice Blog, worth reading it. I have also bookmarked it for the future.

    If you are looking to Work in Australia , Work in Canada, Work in USA, Work in UK, or Work in Ireland then GIEC Global will be the best consultant for you in Australia.

    ReplyDelete
  7. Good One. Worth reading it once.

    If you are looking to Visit to Australia , Visit to Canada, Visit to USA, or Visit to UK then GIEC Global will be the best consultant for you in Australia.

    ReplyDelete
  8. Brother, your content is awesome and very informative. I also have a website , please visit and share you review too
    Brahmrishi is very good website
    jaisana

    ReplyDelete