function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jonathan Wolff 7Jonathan Wolff 7 

Change code to sort datatable by date

Hello, I have a datatable with dates in one column. Can you please help me changing my current code so the sortation functions?
I have no idea how the code is modified in the right way.

My code:
 
<aura:component controller="ApexActivityWrapper" implements="force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordId" access="global">  
    
    <aura:attribute name="taskEventList2" type="object"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInIt}"/>
    <aura:attribute name="mycolumns" type="List"/>

    
    <div style= "font-size: 14px; font-weight: bold; margin-left:15px; margin-top:10px;">
        ActivityList        
    </div>
    <div>
        <aura:if isTrue="{!not(empty(v.taskEventList2))}">
            <lightning:datatable data="{!v.taskEventList2}" 
                                 columns="{!v.mycolumns}" 
                                 keyField="Id"
                                 hideCheckboxColumn="true"/>
            <aura:set attribute="else">
                <div Style="text-align : center">Keine Aufgaben</div>
            </aura:set>
        </aura:if>
    </div>
</aura:component>
 
({
    doInIt : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: "Datum", 			fieldName: "DatumOut", sortable:true,		type: "date-local", typeAttributes:	{month: "2-digit", day: "2-digit" }},           
            {label: 'Typ', 				fieldName: 'TypOut', 	type: 'text'},
            {label: 'Thema', 			fieldName: 'ThemaOut', 	type: 'string', 		typeAttributes: {label: { fieldName: 'sub' }, target: '_blank'}},
            {label: 'Bezug zu', 		fieldName: 'BezugOut', 	type: 'text'},          
            {label: 'Zugewiesen zu', 	fieldName: 'ZugewiesenOut',	type: 'text'},          
        ]);
            var action = component.get("c.ApexActivityWrapper");
			var recordId = component.get('v.recordId');
            action.setParams({ recordId : recordId });
            
            action.setCallback(this, function(response){
            var state = response.getState();
            console.log('state==='+state);
            if(state === "SUCCESS")
            {
            var response = response.getReturnValue();
            console.log('response==='+JSON.stringify(response));          
            component.set("v.taskEventList2", response);
            } else if(state === "INCOMPLETE") {
            	//do something 
            } else if(state === "ERROR") {
            	var error = response.getError();
            	if(error) {
            		console.log("error"+error);
            	}
            }
            });
            $A.enqueueAction(action);
            },
            
            
            
            
            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);
    },
})
 
({
	 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));
        }
    }
})
 
public Class ApexActivityWrapper {    
    @auraEnabled
    public static List<eEventTTask> ApexActivityWrapper (String recordId) {     
        system.debug('recordId =' + recordId);
        List<eEventTTask> taskEventList = new List<eEventTTask>();  
        // Abfrage von Terminen/Events
        for (Event e: [SELECT Id, Subject, ActivityDate, What.Name, Owner.Name FROM Event WHERE Id IN (select EventId from EventRelation where RelationId = :recordId)]) {
            taskEventList.add(new eEventTTask(e.Subject, e.ActivityDate, 'E', e.What.Name, e.Owner.Name));
        }
        // Abfrage von Aufgaben/Tasks
        for (Task t: [SELECT Id, Subject, ActivityDate, What.Name, Owner.Name FROM Task WHERE Id IN (select TaskId from TaskRelation where RelationId = :recordId)]) {
            taskEventList.add(new eEventTTask(t.Subject, t.ActivityDate, 'T', t.What.Name, t.Owner.Name));
        }
        // Abfrage von Email-Messages
       // for (EmailMessage emm: [SELECT Id, Subject, MessageDate, LastModifiedDate FROM EmailMessage WHERE Id IN (select EmailMessageId from EmailMessageRelation where RelationId = :recordId)]) {
        //   taskEventList.add(new eEventTTask(emm.Subject, emm.LastModifiedDate, 'EMM',  emm.Subject, emm.Subject));
      //  }
        // Abfrage von Notizen/Notes
        for(Note n: [SELECT Id, Title, CreatedDate, Createdby.Name, Owner.Name, Parent.Name, ParentId FROM Note WHERE ParentId = :recordId]) {
            taskEventList.add(new eEventTTask(n.Title, date.newInstance(n.CreatedDate.year(), n.CreatedDate.month(), n.CreatedDate.day()), 'N', n.Parent.Name, n.Owner.Name));
        }  
        // Abrage von Anlagen/Dateien (alte Version - wird von Salesforce irgendwann abgestellt)
        for(Attachment a: [SELECT Id, Name, CreatedDate, Createdby.Name, Owner.Name, Parent.Name, ParentId FROM Attachment WHERE ParentId = :recordId]) {
            taskEventList.add(new eEventTTask(a.Name, date.newInstance(a.CreatedDate.year(), a.CreatedDate.month(), a.CreatedDate.day()), 'A', a.Parent.Name, a.Owner.Name));
        }
        // Abfrage von Notizen (neue Version)
        for(ContentDocumentLink c: [SELECT Id, ContentDocumentId, ContentDocument.Title, ContentDocument.createdDate, ContentDocument.Createdby.Name, ContentDocument.FileExtension, LinkedEntity.Id, LinkedEntity.Name FROM ContentDocumentLink WHERE LinkedEntityId = :recordId]) {
            taskEventList.add(new eEventTTask(c.ContentDocument.Title, date.newInstance(c.ContentDocument.CreatedDate.year(), c.ContentDocument.CreatedDate.month(), c.ContentDocument.CreatedDate.day()), 'C', c.LinkedEntity.Name, c.ContentDocument.CreatedBy.Name));
        }
        system.debug('taskEventList' + taskEventList);
        return taskEventList;
    }
    
    public class eEventTTask {
        @AuraEnabled
        public String ThemaOut {get; set;}
        @AuraEnabled
        public Date DatumOut {get; set;}
        @AuraEnabled
        public String TypOut {get; set;}
        @AuraEnabled
        public String BezugOut {get; set;}
        @AuraEnabled
        public String ZugewiesenOut {get; set;}
        
        public eEventTTask(String ThemaIn, Date DatumIn, String TypIn, String BezugIn, String ZugewiesenIn) {         
            ThemaOut 		= ThemaIn;
            DatumOut	 	= DatumIn;
            TypOut			= TypIn;
            BezugOut		= BezugIn;
            ZugewiesenOut	= ZugewiesenIn;
        }
    }
}

 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Janathon,

Can you try the below code. No need to change Apex class for this and I tested it in personal org and it is working as expected.

Component:
 
<aura:component controller="ApexActivityWrapper" implements="force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordId" access="global">  
    
    <aura:attribute name="taskEventList2" type="object"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInIt}"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:attribute name="sortBy" type="String"/>
    <aura:attribute name="sortDirection" type="String"/>
    
    <div style= "font-size: 14px; font-weight: bold; margin-left:15px; margin-top:10px;">
        ActivityList        
    </div>
    <div>
        <aura:if isTrue="{!not(empty(v.taskEventList2))}">
            <lightning:datatable data="{!v.taskEventList2}" 
                                 columns="{!v.mycolumns}" 
                                 keyField="Id"
                                sortedBy="{!v.sortBy}"
        sortedDirection="{!v.sortDirection}"
        onsort="{!c.handleSort}"
                                 hideCheckboxColumn="true"/>
            <aura:set attribute="else">
                <div Style="text-align : center">Keine Aufgaben</div>
            </aura:set>
        </aura:if>
    </div>
</aura:component>

Controller:
 
({
    doInIt : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: "Datum", 			fieldName: "DatumOut", sortable:true,		type: "date-local", typeAttributes:	{month: "2-digit", day: "2-digit" }},           
            {label: 'Typ', 				fieldName: 'TypOut', sortable:true,	type: 'text'},
            {label: 'Thema', 			fieldName: 'ThemaOut',sortable:true, 	type: 'string', 		typeAttributes: {label: { fieldName: 'sub' }, target: '_blank'}},
            {label: 'Bezug zu', 		fieldName: 'BezugOut',sortable:true, 	type: 'text'},          
            {label: 'Zugewiesen zu', 	fieldName: 'ZugewiesenOut',sortable:true,	type: 'text'},          
        ]);
            var action = component.get("c.ApexActivityWrapper");
			var recordId = component.get('v.recordId');
            action.setParams({ recordId : recordId });
            
            action.setCallback(this, function(response){
            var state = response.getState();
            console.log('state==='+state);
            if(state === "SUCCESS")
            {
            var response = response.getReturnValue();
            console.log('response==='+JSON.stringify(response));          
            component.set("v.taskEventList2", response);
            } else if(state === "INCOMPLETE") {
            	//do something 
            } else if(state === "ERROR") {
            	var error = response.getError();
            	if(error) {
            		console.log("error"+error);
            	}
            }
            });
            $A.enqueueAction(action);
            },
            
            
            
            
        handleSort: function(component,event,helper){
            
        var sortBy = event.getParam("fieldName");
   		console.log(sortBy);
        var sortDirection = event.getParam("sortDirection");
   
        component.set("v.sortBy",sortBy);
        component.set("v.sortDirection",sortDirection);
         
        helper.sortData(component,sortBy,sortDirection);
    }
            
            
})

Helper:
({
    sortData : function(component,fieldName,sortDirection){
        var data = component.get("v.taskEventList2");
        console.log(data);
        //function to return the value stored in the field
        var key = function(a) { return a[fieldName]; }
        var reverse = sortDirection == 'asc' ? 1: -1;
         
        data.sort(function(a,b){
                var a = key(a) ? key(a) : '';
                var b = key(b) ? key(b) : '';
                return reverse * ((a>b) - (b>a));
            });
        component.set("v.taskEventList2",data);
        console.log(data);
    }
})

Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,​​​​​​​