Add Sorting in Lightning Data Table in Lightning Component Salesforce

How to add Sorting in Lightning Data Table ?

Hello everyone, in this blog post you will learn to add Sorting in Lightning Data Table in a custom Lightning Component.

Please follow the code below : 

Apex : LightningDataTableCTRL.apxc

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public class LightningDataTableCTRL {
    @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;}
    }
}


Component : LightningDataTable.cmp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<aura:component controller="LightningDataTableCTRL" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <aura:attribute name="recordList" 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}" />
    
    <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>


JS : LightningDataTableController.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
({
    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);
    },
    
})

Helper : LightningDataTableHelper.js

 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
({
    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);
            }
        });
        $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));
        }
    }
})

Output




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

32 Comments

  1. This is helpful. Thanks for the code. I am a salesforce trainee in learning. Can you add pagination with page number ?

    ReplyDelete
    Replies
    1. Hi Sahil, yes I can. I will share the details here shortly. Follow my channel if you like the blog content : https://www.youtube.com/channel/UCej2O8W9gR-Bcsne9cYhNqw

      Delete
    2. Check the link for pagination with page numbers
      https://www.salesforcebolt.com/2020/04/how-to-add-pagination-in-lightning-data.html

      Delete
  2. Hi Sahil. Can we make other field sortable too. Here, we want the createdDate Field the default sortable. How we can achieve that.

    ReplyDelete
    Replies
    1. Hi, yes we can make other field sort abletoo. To make createdDate field default sortable you need to mention it in the SOQL in apex like "ORDER BY CreatedDate"

      Delete
    2. Otherwise by default it will make the name field sortable. Is there any solution we can do it without making changes in apex,i.e, without writing "ORDER BY CreatedDate" and achieving it through Lightning.

      Delete
    3. Yes you can, please check in component code at line number 4 we are having sortedBy attribute which is default assign to Name. You can change the value there from "Name" to "CreatedDate". It will do the trick.

      Delete
  3. Can we colour a particular Column. Any Idea.
    Example: CreatedDate: Green And Name= Yellow

    ReplyDelete
    Replies
    1. Yes we can add colors using custom css for data tables.

      Delete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Can you share some link or references which can help in these.

    ReplyDelete
    Replies
    1. Hey try this link https://www.salesforcebolt.com/2020/06/change-background-color-in-lightning.html

      Delete
  6. Can you describe/Share some references about Colouring particular Column. It is for learning purpose.Your effort will be appreciated .

    ReplyDelete
    Replies
    1. Hey try this link https://www.salesforcebolt.com/2020/06/change-background-color-in-lightning.html

      Delete
  7. Hello, Thanks for this - However i experience an issue when creating LightningDTApp* . When clicking on Preview (4th minute on your video) i receive no results (blank)

    ReplyDelete
    Replies
    1. Hi Alex, could you please check if you are having data in your org. Also please try it once by checking the size of the list in logs.

      Delete
    2. This comment has been removed by the author.

      Delete
    3. Thank you. Managed to accomplish. Is there a way of adding a hyperlink so that the once once he types on the Account he can click on the Account name and take him to the relevant record?
      Also - How can we add fields from other objects to the component? (e.g. add some fields from contact object or another object)

      Delete
    4. Hi Alex,
      If you need the hyperlink in the datatable than make sure it's type is lookup. Or you can use table and run the iteration. In the iteration you can use anchor tag to make it clickable.
      To add fields from other objects like Contact, you just have to change the query in apex and arrange the fields in the component accordingly.

      Delete
    5. You need to add 'type' and 'attributes' to the column:
      {label: 'Account Name', fieldName: 'Name', type: 'url', sortable:true,
      typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'}},

      [Thanks, Kapil, for an excellent post].

      Delete
    6. You might also need to add a link address when the result is returned

      var results = response.getReturnValue();
      results.forEach(function(record){
      record.linkMyObject = '/'+record.wMyObjectId;
      });

      {label: 'Name', fieldName: 'linkMyObject', type: 'url', sortable:true,
      typeAttributes: {label: { fieldName: 'MyObjectName' }, target: '_blank'}},

      Delete
  8. Hi Kapil,

    Sorting on Created date is not working as expected, could you please check once.

    Thanks,
    Raj

    ReplyDelete
    Replies
    1. Hi Rajesh, sure I will check it out and let you know.

      Delete
  9. Many thanks for this.. but i didn't understand sorting logic

    ReplyDelete
    Replies
    1. Glad it helped ! The sorting logic, take it like changing position of each value on client side in the list.

      Delete
  10. Hi, thank you for this code, I used and tested, and works! But, I find a little "bug" that hes not sorting if have null or empty value..

    ReplyDelete
    Replies
    1. Hey thanks for sharing it here, I will check and update the code accordingly.

      Delete
  11. Hi, thank you for this code and explanation! Could we also add a 'Refresh' button in the component?

    ReplyDelete