0

I have an LWC that I created but the sorting is only works with ascending. Can someone look at this and tell me what I am doing wrong?

html code

<template>
<div class="slds-m-top_medium line">
    <lightning-card variant="Narrow" title ="Profile Team Member Audits" icon-name="standard:account">
        <div class="sds-scrollable">
            <lightning-datatable data={history}
                key-field="Id"
                columns={columns}
                sorted-direction={sortDirection}
                onsort={handleSort}
                hide-checkbox-column="true"
                min-column-width= 280>
            </lightning-datatable>
        </div>
    </lightning-card>
</div>

js code

 import {LightningElement,wire, api, track} from 'lwc';
    import getPTMAudits from 
   "@salesforce/apex/GetProfileTeamMemberAuditController.getProfileTeamMemberAuditList"   

   const Columns = [{label: 'Profile Team Member Audit Name', fieldName: 'name', sortable: 
   "true"},
   {label: 'Created by', fieldName: 'createdBy', sortable: "true"}, 
   {label: 'Created Date', fieldName: 'createdDate', sortable: "true"}, 
   {label: 'Event Type', fieldName: 'eventType', sortable: "true"}, 
   {label: 'Last Modified by', fieldName: 'lastModifiedBy', sortable: "true"}, 
   {label: 'Case Access', fieldName: 'caseAccess', sortable: "true"}, 
   {label: 'New Role', fieldName: 'newRole', sortable: "true"}, 
   {label: 'New ProfileTeamMemberStatus', fieldName: 'nptms', sortable: "true"}, 
   {label: 'Opportunity Access', fieldName: 'opptyAccess', sortable: "true"}, 
   {label: 'Original Role', fieldName: 'originalRole', sortable: "true"}, 
   {label: 'Original Profile TeamMember Status', fieldName: 'optms', sortable: "true"}, 
   {label: 'Owner', fieldName: 'owner', sortable: "true"}, 
   {label: 'Profile Access', fieldName: 'profileAccess', sortable: "true"}, 
   {label: 'Profile Name', fieldName: 'profileName', sortable: "true"}, 
   {label: 'Profile Team Member Name', fieldName: 'profileTeamMemberName', sortable: "true"}, 
   {label: 'Title', fieldName: 'title', sortable: "true"}
   ];

   export default class ProfileTeamMemberAuditRelatedList extends LightningElement { 
    @api recordId; // Id of the record whose related list is displayed 
    @track sortBy; 
    @track columns = Columns
    @track filterText = ''; // Data to be displayed in the related list 
    @track history;
    @track sortDirection; 
    @track filteredData = [];

    @wire(getPTMAudits, {profileId: '$recordId'}) 
    wiredRecord({ error, data }){ 
        if (data){ 
            //console.log("data >>" + JSON.stringify(data));
            // Extract and set related list data 
            this.history = data.map(row => {
                const name = row.Name;
                const createdBy = row.CreatedBy.Name;
                const createdDate = row.CreatedDate;
                const eventType = row.EventType__c;
                const lastModifiedBy = row.LastModifiedBy.Name;
                const caseAccess = row.CaseAccess__c;
                const newRole = row.NewRole__c;
                const nptms = row.NewProfileTeamMemberStatus__c;
                const opptyAccess = row.OpportunityAccess__c;
                const originalRole = row.OriginalRole__c;
                const optms = row.OriginalProfileTeamMemberStatus__c;
                const owner = row.Owner.Name;
                const profileAccess = row.ProfileAccess__c;
                const profileName = row.ProfileName__r.Name;
                const profileTeamMemberName = row.ProfileTeamMemberName__r.Name;
                const title = row.Title__c;
                return {...row,name,createdBy,createdDate,eventType,lastModifiedBy,caseAccess,newRole,nptms,opptyAccess,originalRole,optms,owner,profileAccess,profileName,profileTeamMemberName,title};
            })
            
            this.error = undefined;
            //console.log("history >>" + JSON.stringify(this.history));
            //return {auditName, createdBy,createdDate,eventType,lastModifiedBy,caseAccess,newRole,newProfileTeamMemberStatus,opptyAccess,originalRole,originalProfileTeamMemberStatus,owner,profileAccess,profileName,profileTeamMemberName,title};
        }
        else if(error){
            console.error(error);
            this.history = undefined; 
        }     
    } // Load ProfileTeamMemberAudit records for the given profileId 
    

    // Handle sorting change 
    handleSort(event) {
        this.sortBy = event.detail.fieldName;
        this.sortDirection = event.detail.sortDirection;
        console.log('field >>> ' + event.detail.fieldName);
        console.log('sort direction >>> ' + event.detail.sortDirection);
        this.sortData(this.sortBy, this.sortDirection);
    } 

    handleFilterChange(event) {
        this.filterText = event ? event.target.value : this.filterText; 
        this.filterData(); 
    } 
    
    sortData(fieldname, direction) { 
        let parseData = JSON.parse(JSON.stringify(this.history));
        // Return the value stored in the field
        let keyValue = (a) => {
            return a[fieldname];
        };
        // cheking reverse direction
        let isReverse = direction === 'asc' ? 1: -1;
        // sorting data
        parseData.sort((x, y) => {
            x = keyValue(x) ? keyValue(x) : ''; // handling null values
            y = keyValue(y) ? keyValue(y) : '';
            // sorting values based on direction
            return isReverse * ((x > y) - (y > x));
        });
        this.history = parseData;
    }
    
    // Filter data based on the entered text 
    filterData() {
        this.filteredData = this.history.filter(item => Object.values(item).some(value => value && value.toString().toLowerCase().includes(this.filterText.toLowerCase()) ) );
        this.sortData(); // Reapply sorting after filtering 
    } 
}

Apex code

public with sharing class GetProfileTeamMemberAuditController {
    @AuraEnabled(cacheable = true)
    public static List<profileTeamMemberAudit__c> getProfileTeamMemberAuditList(Id profileId){
        List<profileTeamMemberAudit__c> ptmAudit = new List<ProfileTeamMemberAudit__c>();
            ptmAudit = [SELECT Id, CaseAccess__c,CreatedBy.Name,CreatedDate,EventType__c,LastModifiedBy.Name,Name,NewProfileTeamMemberStatus__c,NewRole__c,OpportunityAccess__c,
                        OriginalProfileTeamMemberStatus__c,OriginalRole__c,Owner.Name,ProfileAccess__c,ProfileName__r.Name,ProfileTeamMemberName__r.Name,Title__c 
                        FROM ProfileTeamMemberAudit__c Where ProfileName__c =: profileId];
        return ptmAudit;
    }
}

debug screenshot From what I can tell everything looks correct, but when I click on the column label I get the sort direction as "asc" in the console debug. I also don't see the arrow point down in the UI. Please let me know if you see something that I am doing wrong. Thank you in advance.

1 Answer 1

1

You're missing sorted-by. If you don't set both sorted-by and sorted-direction, the table will not know the correct parameters to send to your event handler.

<lightning-datatable data={history}
    key-field="Id"
    columns={columns}
    sorted-by={sortBy}
    sorted-direction={sortDirection}
    onsort={handleSort}
    hide-checkbox-column="true"
    min-column-width= 280>
</lightning-datatable>
1
  • Thank you! That solved it. I don't know why I missed that. Everything works now.
    – user61039
    Commented Jan 25 at 14:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .