
How To Implement Column Sorting In Salesforce Lightning DataTable
Hi guys, Today in this post we are going to learn how we can implement custom column sorting in salesforce ‘lightning:datatable’ lightning base component.
From developer console >> file >> new >> Apex Class
Apex Controller : SortableAccountTableController.apxc
/* * Date : 3/6/2019 * API : 45 * Source : sfdcMonkey.com */ public class SortableAccountTableController { // wrapper class public class AccountWrapper{ @AuraEnabled public String message; @AuraEnabled public List<Account> accountsList; @AuraEnabled public Boolean success; } //Return account records and message to be displayed in toast @AuraEnabled public static AccountWrapper getAccounts(){ AccountWrapper accountWrapper = new AccountWrapper(); try{ accountWrapper.accountsList = [SELECT ID,Name,AccountSource,Rating,NumberOfEmployees FROM Account ORDER BY AnnualRevenue DESC NULLS LAST LIMIT 50]; accountWrapper.message = 'Account records are retrieved '; accountWrapper.success = true; } catch(Exception e){ accountWrapper.message = e.getMessage(); accountWrapper.success = false; } return accountWrapper; } }
Check Also : Powerful Lightning Datatable base component – Example Using Fieldset
From developer console >> file >> new >> Lightning Component
Lightning Component : sortableAccountTable.cmp
<!-- * Date : 3/6/2019 * API : 45 * Source : sfdcMonkey.com --> <aura:component controller="SortableAccountTableController" description="Account table with column sorting example" implements="flexiPage:availableForAllPageTypes"> <aura:handler name="init" value="{!this}" action="{!c.onInit}"/> <!--aura attributes--> <aura:attribute name="accountColumns" type="List"/> <aura:attribute name="accountData" type="Object"/> <aura:attribute name="sortBy" type="String"/> <aura:attribute name="sortDirection" type="String"/> <!--Page header--> <div class="slds-page-header" role="banner"> <span class="slds-text-heading_medium">Accounts List</span> <span class="slds-page-header__title">Top 50 Accounts</span> </div> <!--Lightning data table markup--> <lightning:datatable aura:id="accountTable" keyField="Id" hideCheckboxColumn="true" columns="{!v.accountColumns}" data="{!v.accountData}" sortedBy="{!v.sortBy}" sortedDirection="{!v.sortDirection}" onsort="{!c.handleSort}"/> </aura:component>
JavaScript Controller : sortableAccountTableController.js
/* * Date : 3/6/2019 * API : 45 * Source : sfdcMonkey.com */ ({ onInit : function(component,event,helper){ // Setting column information.To make a column sortable,set sortable as true on component load component.set("v.accountColumns",[ { label : 'Name', fieldName : 'Name', type : 'text', sortable : true }, { label : 'Account Source', fieldName : 'AccountSource', type : 'text', sortable : true }, { label : 'Rating', fieldName : 'Rating', type : 'text', sortable : true }, { label : 'Employees', fieldName : 'NumberOfEmployees', type : 'number', sortable : true } ]); // call helper function to fetch account data from apex helper.getAccountData(component); }, //Method gets called by onsort action, handleSort : function(component,event,helper){ //Returns the field which has to be sorted var sortBy = event.getParam("fieldName"); //returns the direction of sorting like asc or desc var sortDirection = event.getParam("sortDirection"); //Set the sortBy and SortDirection attributes component.set("v.sortBy",sortBy); component.set("v.sortDirection",sortDirection); // call sortData helper function helper.sortData(component,sortBy,sortDirection); } })
JavaScript Helper : sortableAccountTableHelper.js
/* * Date : 3/6/2019 * API : 45 * Source : sfdcMonkey.com */ ({ getAccountData : function(component){ //Load the Account data from apex var action = component.get("c.getAccounts"); var toastReference = $A.get("e.force:showToast"); action.setCallback(this,function(response){ var state = response.getState(); if(state == "SUCCESS"){ var accountWrapper = response.getReturnValue(); if(accountWrapper.success){ //Setting data to be displayed in table component.set("v.accountData",accountWrapper.accountsList); toastReference.setParams({ "type" : "Success", "title" : "Success", "message" : accountWrapper.message, "mode" : "dismissible" }); } // handel server side erroes, display error msg from response else{ toastReference.setParams({ "type" : "Error", "title" : "Error", "message" : accountWrapper.message, "mode" : "sticky" }); } } // handel callback error else{ toastReference.setParams({ "type" : "Error", "title" : "Error", "message" : 'An error occurred during initialization '+state, "mode" : "sticky" }); } toastReference.fire(); }); $A.enqueueAction(action); }, sortData : function(component,fieldName,sortDirection){ var data = component.get("v.accountData"); //function to return the value stored in the field var key = function(a) { return a[fieldName]; } var reverse = sortDirection == 'asc' ? 1: -1; // to handel number/currency type fields if(fieldName == 'NumberOfEmployees'){ data.sort(function(a,b){ var a = key(a) ? key(a) : ''; var b = key(b) ? key(b) : ''; return reverse * ((a>b) - (b>a)); }); } else{// to handel text type fields data.sort(function(a,b){ var a = key(a) ? key(a).toLowerCase() : '';//To handle null values , uppercase records during sorting var b = key(b) ? key(b).toLowerCase() : ''; return reverse * ((a>b) - (b>a)); }); } //set sorted data to accountData attribute component.set("v.accountData",data); } })
- check code comments
Datatable Sorting Output :
Related Resources :
Other popular Post :
- Add Delete Row Dynamic In Lightning Component : Sample Code
- Fieldset and Legend Not Display Properly In Lightning Component -fix/workaround
- Delete Multiple Records Using Checkbox In Lightning Component
- How to Use Wrapper Class In Lightning Component -Inner Class Example
- Custom Record Type Selection Lightning Component with force:createRecord event
Like our facebook page for new post updates. & Don’t forget to bookmark this site for your future reference.
if you have any suggestions or issue with it, you can post in comment box.
Happy Learning
About The contributor:
I have 3.5 years of experience and working in lightning for the past 1 year. I am working as a developer in Deloitte.
Skills : Apex ,lightning , visualforce,sales cloud,JavaScript,Einstein analytics
Post By Kiran :
4 comments
I am getting an error-
Error in $A.getCallback() [Cannot read property ‘setParams’ of undefined] Callback failed: apex://SortableAccountTableController/ACTION$getAccounts Failing descriptor: {c:sortableAccountTable}
$A.get(“e.force:showToast”) event is handled by the one.app container. It’s supported in Lightning Experience, Salesforce app, and Lightning communities only.
if you are using this in standalone app or lightning out mode then add condition for it like : if(toastReference != undefined)
Hi Kiran,
Could you please explain Me three things:
In the function sortData in JS Helper:
WHat does the lines do?
53> var reverse = sortDirection == ‘asc’ ? 1: –1;
60> return reverse * ((a>b) – (b>a));
67> return reverse * ((a>b) – (b>a));
Please kindly explain sir.
Regards,
Siddhartha
How to use parent field or lookup reation field of child custom object in client side controller. Ex: Parent : Course__c , Child : Class__c , field to use in client side controller : Course__r.category__c.