Hello Everyone, In this post, we will see a code example that shows you, how you can implement sorting on lightning datatable columns. This example is very easy to implement in lightning components. So without wasting time let's begin,
Column sorting in lightning:datatable
For this task, I have create an apex class and a lightning component. In apex class, code simply return list of account that used in component. The key point is placed in component that help me to sort the datatable column.
1. Navigate to Developer Console | File | New | Apex Class and create a new apex class named DatatableHandler and replace the following code.
DatatableHandler.apxc
public class DatatableHandler {
@AuraEnabled
public static List<Account> getAccounts(){
return [SELECT Id,Name,Industry,AccountNumber,CreatedDate FROM Account limit 10];
}
}
2. Navigate to Developer Console | File | New | Lightning Component and create a new lightning component named ColumnSorting and replace the following block of code in their related files.
ColumnSorting.cmp
<aura:component controller="DatatableHandler" implements="force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordId" access="global" >ColumnSortingController.js
<aura:attribute name="results" type="Account[]"/>
<aura:attribute name="mycolumns" type="List"/>
<aura:attribute name="sortedBy" type="String" default="Name"/>
<aura:attribute name="sortedDirection" type="string" default="asc" />
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<lightning:layout multipleRows="true" horizontalAlign="center">
<lightning:layoutItem padding="around-small" size="12">
<lightning:datatable keyField="id" data="{!v.results}"
columns="{!v.mycolumns}"
resizeColumnDisabled="true"
hideCheckboxColumn="true"
onsort="{!c.sortColumn}"
sortedBy="{!v.sortedBy}"
sortedDirection="{!v.sortedDirection}"
/>
</lightning:layoutItem>
</lightning:layout>
</aura:component>
({ColumnSortingHelper.js
doInit : function(component, event, helper) {
component.set('v.mycolumns', [
{label: 'Name', fieldName: 'Name',type: 'text',sortable:true},
{label: 'Industry', fieldName: 'Industry',type: 'text',sortable:true},
{label: 'AccountNumber', fieldName: 'AccountNumber',type: 'text',sortable:true},
{label: 'Created Date', fieldName: 'CreatedDate',type: 'date',sortable:true,
typeAttributes:{day:'numeric',month:'short',year:'numeric',hour:'2-digit',minute:'2-digit',second:'2-digit',hour12:true}}
]);
var action=component.get("c.getAccounts");
action.setCallback(this,function(e){
if(e.getState()=='SUCCESS'){
var results=e.getReturnValue();
console.log(results);
if(results.length>0){
component.set('v.results', results);
}
}
});
$A.enqueueAction(action);
},
sortColumn : function (component, event, helper) {
var fieldName = event.getParam('fieldName');
var sortDirection = event.getParam('sortDirection');
component.set("v.sortedBy", fieldName);
component.set("v.sortedDirection", sortDirection);
helper.sortData(component, fieldName, sortDirection);
},
})
({
sortData: function (component, fieldName, sortDirection) {
var fname = fieldName;
var data = component.get("v.results");
var reverse = sortDirection !== 'asc';
data.sort(this.sortByfield(fieldName, reverse))
component.set("v.results", data);
},
sortByfield: 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));
}
},
})
3. Preview component to see the output.
Output:
Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.
2 Comments
The default sort separates lower and uppercase values into the equivalent of two sorted lists.
ReplyDeleteTo use different sorting algorithms, add the 'primer' parameter or change the function
See: sfdcfox's answer in https://salesforce.stackexchange.com/questions/362001/what-is-the-third-parameter-primer-in-the-lightning-datatable-sort-example.
sortByfield: 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));
a = key(a);
a = (""+a).toLowerCase();
b = key(b);
b = (""+b).toLowerCase();
return a, b, reverse * ((a > b) - (b > a));
}
},//sortByfield
Null values are getting sorted with the above logic. Also Data values are not getting sorted.
ReplyDeletePost a Comment