1

I have built a data table similar to something I have done before but now my sorting is not working and I cant figure it out.

The difference between this data table and other I have built before is this lives within a tab on a lightning record page but this code is repurposed from older projects. Is there anything new about soring a data table or anything obviously wrong with my code? This is my apex class -

    public with sharing class WhitespacesController {
    @AuraEnabled(cacheable=true)
    public static List<Whitespace__c> getWhitespaces(Id accountId) {
        return [SELECT Id, Name, Cost__c, date__c, Product__c FROM Whitespace__c WHERE Account_Plan__c = :accountId];
    }

    @AuraEnabled
    public static void updateWhitespaces(List<Whitespace__c> whitespaces) {
        update whitespaces;
    }
}

my LWC files are below-

.js

import { LightningElement, api, wire, track } from 'lwc';
import getWhitespaces from '@salesforce/apex/WhitespacesController.getWhitespaces';
import updateWhitespaces from '@salesforce/apex/WhitespacesController.updateWhitespaces';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { refreshApex } from '@salesforce/apex';

export default class RelatedWhitespacesTable extends LightningElement {
    @api recordId;
    @track whitespaces = [];
    sortedBy;
    sortedDirection = 'asc'; // Default sorting direction
    columns = [
        { label: 'Whitespace Name', fieldName: 'Name', editable: true, sortable: true }, // Enable sorting
        { label: 'Date', fieldName: 'date__c', type: 'date-local', editable: true, sortable: true },
        { label: 'Product', fieldName: 'Product__c', editable: true, sortable: true },
        { label: 'Cost', fieldName: 'Cost__c', type: 'currency', typeAttributes: { currencyCode: 'USD' }, cellAttributes: { style: 'text-align: left;' }, editable: true, sortable: true }
    ];

    _wiredWhitespacesResult;

    @wire(getWhitespaces, { accountId: '$recordId' })
    wiredWhitespaces(result) {
        this._wiredWhitespacesResult = result; // Store the wire service result

        if (result.data) {
            this.whitespaces = result.data;
        } else if (result.error) {
            // Handle error
        }
    }

    handleSave(event) {
        const updatedFields = event.detail.draftValues;

        // Call Apex method to update records
        updateWhitespaces({ whitespaces: updatedFields })
            .then(() => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Whitespaces updated',
                        variant: 'success'
                    })
                );

                // Clear all draft values
                this.template.querySelector('lightning-datatable').draftValues = [];

                // Refresh data
                return refreshApex(this._wiredWhitespacesResult);
            })
            .catch(error => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error updating record',
                        message: error.body.message,
                        variant: 'error'
                    })
                );
            });
    }

    doSorting(event) {
        this.sortBy = event.detail.fieldName;
        this.sortDirection = event.detail.sortDirection;
        this.sortData(this.sortBy, this.sortDirection);
    }

    sortData(fieldname, direction) {
        let parseData = JSON.parse(JSON.stringify(this.data));
        // 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.data = parseData;
    }    
}

HTML

<template>
    <lightning-card title="Related Whitespaces">
        <lightning-datatable
            key-field="Id"
            data={whitespaces}
            columns={columns}
            hide-checkbox-column="true"
            onsave={handleSave}
            draft-values={draftValues}>
        </lightning-datatable>
    </lightning-card>
</template>
1
  • The linked answer is for Aura, but the same principle applies--you must bind sortedBy and sortedDirection (in LWC, sorted-by and sorted-direction), and you must set the values in your controller each time onsort is called.
    – sfdcfox
    Dec 22, 2023 at 20:06

0

Browse other questions tagged .