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 date table rows by date

Hello, I want to sort my datatable-component by date. I already tried to implement sort-function in controller like in: in: https://www.salesforcebolt.com/2020/04/add-sorting-in-lightning-data-table.html (https://www.salesforcebolt.com/2020/04/add-sorting-in-lightning-data-table.html" style="color:#0563c1; text-decoration:underline)


Could you tell mehow to change my code to make the sorting of the rows descending by date?
 
<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 Janathan,

I have answerd the same question in the below below link. Can you check it and let me know if you face any issue.

Please close this question thread by marking this as best answer as it avoids duplicate efforts.

https://developer.salesforce.com/forums?id=9062I000000UiUL

You can sort the field based on what ever field you select Sort direction.



Thanks,