0

Im having this anoying problem where the OnSort of the lightning data table changed but the data still not render.  Below are my codes: Please help, Thanks! HTML 

<lightning-datatable class="slds-scrollable_none slds-table_striped" 
                    key-field="id" 
                    data={data} 
                    columns={columns} 
                    onrowaction={handleRowAction}

                    onsort={onClickColumnToSort}
                    sorted-by={sortedBy}
                    sorted-direction={sortedDirection}
                    hide-checkbox-column

                     > 
                </lightning-datatable>

JS

const columns = [

{ label: 'CRU', fieldName: 'Url', type: 'url', sortable: true, typeAttributes: { label: { fieldName: 'CRU' }, target: '_self' } },
{ label: 'Building Name', fieldName: 'BusinessUnitName', type: 'text', sortable: true },
{ label: 'Tenant Name', fieldName: 'TenantName', type: 'text', sortable: true},
{ label: 'Project Stage', fieldName: 'Stage__c', type: 'text', sortable: true},
//{ label: 'LLW Complete', fieldName: 'LLWPercentComplete', type: 'text'},
//{ label: 'Drawings Complete', fieldName: 'DrawingsPercentComplete', type: 'text' },
//{ label: 'TW Complete', fieldName: 'TWPercentComplete', type: 'text' },
{ label: 'Project % Complete', fieldName: 'ProjectPercentComplete', type: 'text' , sortable: true},
//{ label: 'Deal', fieldName: 'DealUrl', type: 'url', typeAttributes: { label: { fieldName: 'DealName' }, target: '_self' } },
{ label: 'Deal', fieldName: 'DealName', type: 'text' , sortable: true},
{ label: 'Deal Stage', fieldName: 'DealStage', type: 'text' , sortable: true},
{ label: 'Area', fieldName: 'Area__c', type: 'number' , sortable: true},
{
    label: '', type: 'button-icon', initialWidth: 20,
    typeAttributes: {
        iconName: 'utility:edit',
        label: 'Edit',
        name: 'Edit',

    }
}

];

export default class RdcProjectList extends NavigationMixin (LightningElement) {

@track columns = columns;

@track data ;
@track error;
@track recordId;
@track record = {};

//@track projectCount = 0;
@track loaded = false;
@track showModal = false;

@api projectMemberOnly = false;
@api status = 'open-0'; // accepts 'open-0' or 'open-1' or 'closed-0' or 'closed-1' values

userId = Id;
_propertyId = ''; 
_propertyName = '';
_projectCount = 0;
_status = 'open'; // status for passing to getProjectsList function

//for paginator
@api currentpage;
@api pagesize;
@api totalrecords;
@track totalpages;
_isSearchChangeExecuted = false;
_localCurrentPage = this.currentpage;

//for sorting funtions
@api hideCheckboxColumn;
@api sortedBy;
@api sortedDirection;
@api keyField;
@track assetId='';

/** Wired Apex result so it can be refreshed programmatically */
@track wiredResult;


@wire(getProjectsList, { assetId: '$propertyId', userId: '$userId', status: '$_status', hasProjectMembership: '$projectMemberOnly', page: '$currentpage', pageSize: '$pagesize' }) 
wiredData(result) {
    this.wiredResult = result;
    if (result.data) {

        if (this._isSearchChangeExecuted && this._localCurrentPage === this.currentpage) {
            return;
        }
        this._isSearchChangeExecuted = true;
        this._localCurrentPage = this.currentpage;

        this.data = this.flattenData(result.data);
        this.error = undefined;
        this._projectCount = result.data.length;
        this.loaded = true;

        this.getRecordCount();

    } else if (result.error) {
        this.error = result.error;
        this.data = undefined;
        this.loaded = true;
    }
    else {
        this.loaded = true;
        this.data = undefined;
        this.error = undefined;
        this.totalrecords = 0;
        this.totalpages = 0;
    }
}
//for sorting



// for pagination
// get total record count
getRecordCount() {
    getRecordCount({ assetId: this.propertyId, status: this._status, hasProjectMembership: this.projectMemberOnly })
        .then(count => {
            if (count !== 0 && count !== undefined) {
                this.totalrecords = count;
                this.totalpages = Math.ceil(this.totalrecords / this.pagesize);
            }
            else {
                this.totalpages = 1;
                this.totalrecords = 0;
            }

            const event = new CustomEvent('recordsloaded', {
                detail: { count: this.totalrecords, tab: 'projects', page: this._localCurrentPage }
            });
            this.dispatchEvent(event);
        })
        .catch(error => {
            this.error = error;
        });

}

// used to force refresh of data when changing tabs
@api
forceRefresh() {
    this._isSearchChangeExecuted = false;
    this.currentpage = 1;
}

flattenData(arr) {
    let tmpData = [];
    tmpData.push(arr);

    tmpData = arr.map(
        row => Object.assign({ 
            "Url": '/' + row.Id,
            "CRU": row.CRU__c == null ? row.Name : row.CRU__c,
            "TenantName": row.Tenant_Name__r == null ? '' : row.Tenant_Name__r.Name , 
            "BusinessUnitName": row.Business_Unit__r.Name,
            "DealName": row.Opportunity__r ? row.Opportunity__r.Name : '',
            "DealStage": row.Opportunity__r ? row.Opportunity__r.StageName : '',
            "LLWPercentComplete": row.Percentage_Complete_Landlord__c !== undefined ? row.Percentage_Complete_Landlord__c + '%' : '0%',
            "DrawingsPercentComplete": row.Percentage_Complete_Drawings__c !== undefined ? row.Percentage_Complete_Drawings__c + '%' : '0%',
            "TWPercentComplete": row.Percentage_Complete_Tenant__c !== undefined ? row.Percentage_Complete_Tenant__c + '%' : '0%',
            "ProjectPercentComplete": row.Project_Percentage_Complete__c !== undefined ? row.Project_Percentage_Complete__c + '%' : '0%',
            "DealUrl": row.Opportunity__r ? '/' + row.Opportunity__r.Id : ''  
        }, row)
    );
    return tmpData;
}

set propertyName(value) {
    this._propertyName = value;
}

@api 
get propertyName() {
    return this._propertyName;
}


// Use set and get to process the value every time it's
// requested while switching between properties
set propertyId(value) {
   this._propertyId = value;
    this._isSearchChangeExecuted = false;
    this.currentpage = 1;
}

// getter for propertyId
@api 
get propertyId(){
    if (this._propertyId === undefined || !this._propertyId)
        return '';
    return this._propertyId;
}

@api
getProjectCount() {
    return this._projectCount;
}

//option values based on project status (open/closed) and project team member (1=user is team member on project, 0=all projects)
get options() {
    return [
        { label: 'My Open Projects', value: 'open-1' },
        { label: 'My Closed Projects', value: 'closed-1' },
        { label: 'All Open Projects', value: 'open-0' },
        { label: 'All Closed Projects', value: 'closed-0' }];
}


handleStatusChange(event) {
    let opts = event.detail.value.split("-");

    if (opts) {
        this._status = opts[0];
        this.loaded = false;

        // eslint-disable-next-line eqeqeq
        let boolMemberOnly = !!(opts[1] == "1");
        this.projectMemberOnly = boolMemberOnly;
    }


    //this._isSearchChangeExecuted = false;
    //this.currentpage = 1;

    //const evt = new CustomEvent('pagereset');
    //this.dispatchEvent(evt); 
}




get projectsExist() {
    if (this.data !== undefined && this.data !== null && this.data.length > 0) {
        return true;
    }
    return false;
}

handleNewProjectClick()
{
    this[NavigationMixin.Navigate]({
        type: 'standard__objectPage',
        attributes: {
            objectApiName: 'RDC_Project__c',
            actionName: 'new'
        },
    });
}

handleRowAction(event) {
    const actionName = event.detail.action.name;

    const row = event.detail.row;
    this.record = row;
    switch (actionName) {
        case 'Open':
            //this.openRecord();
            break;
        case 'Edit':
            //open modal window to edit project
            this.showModal = true;
            //this.loadProjectRecord();
            break;
        // case 'Delete':
        //     // eslint-disable-next-line no-alert
        //     if (window.confirm('Are you sure you want to delete this project?')) {
        //         this.deleteProject();
        //     }
        //     break;
        default:
    }

}

@api 
refreshData() {
    return refreshApex(this.wiredResult);
}


// deleteProject() {

//     // eslint-disable-next-line no-console
//     console.log('delete project Id ' + this.record.Id);

//     deleteRecord(this.record.Id)
//         .then(() => {
//             this.dispatchEvent(
//                 new ShowToastEvent({
//                     title: 'Success',
//                     message: 'Record ' + this.record.Name + ' was deleted.',
//                     variant: 'success',
//                 }),
//             );
//             this.refreshData();
//         })
//         .catch(error => {
//             this.dispatchEvent(
//                 new ShowToastEvent({
//                     title: 'Error deleting record ' + this.record.Name,
//                     message: error.message,
//                     variant: 'error',
//                 }),
//             );
//         });
// }

closeModal() {
    this.showModal = false;
}

handleRecordSubmit(event) {
    // eslint-disable-next-line no-alert
    //alert('form submit');
    event.preventDefault();       // stop the form from submitting
    const fields = event.detail.fields;
    this.template.querySelector('lightning-record-edit-form').submit(fields);
    this.showModal = false;
    this.refreshData();

}
// loadProjectRecord() {
//     getProject( { recordId : this.record})
//         .then(result => {
//             this.assets = result;
//             this._propertyCount = this.assets.length;
//         })
//         .catch(error => {
//             this.error = error;
//         });
// }

handleSuccess() {
    this.dispatchEvent(
        new ShowToastEvent({
            title: 'Success',
            message: 'Project updated successfully!',
            variant: 'success'
        })
    );
    this.showModal = false;
    this.refreshData();
}

handleSave() {

    const fields = {};
    fields[Id] = this.record.Id;
    const recordInput = { fields };

    updateRecord(recordInput)
        .then(() => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: 'Project updated',
                    variant: 'success'
                })
            );
            // Clear all draft values
            this.draftValues = [];

            // Display fresh data in the datatable
            this.refreshData();
        }).catch(error => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error creating record',
                    message: error.body.message,
                    variant: 'error'
                })
            );
        });
}
@api
onClickColumnToSort(event){
    var fieldName = event.detail.fieldName;
    var sortDirection = event.detail.sortDirection;
    this.sortedBy = fieldName;
    this.sortedDirection = sortDirection;
    this.wiredResult = this.sortData(fieldName, sortDirection);

    this.wiredResult =JSON.parse(JSON.stringify(this.wiredResult));

}

sortData(fieldName, sortDirection) {
     var dataToSort =(this.wiredResult);
     dataToSort=JSON.parse(JSON.stringify(dataToSort));

     window.console.log(`parse data = ${dataToSort}`);
    let reverse = sortDirection !== 'asc';//toggle previous direction on every click on column

    [].slice.call(dataToSort).sort(this.sortBy(fieldName, reverse));
     //refreshApex(this.dataToSort);


    return dataToSort;

 }

 sortBy(field, reverse, primer) {
     var key = primer ?function(x) { return primer(x[field])} : function(x) {return x[field]};
         reverse = !reverse ? 1 : -1;
         window.console.log('key- '+key+' ; field - '+field+' ; reverse - '+reverse);
         return function (a, b) {

             return a = key(a),b = key(b),reverse * ((a > b) - (b > a));//eslint-disable-line
         }
 }   

}

  • Please make sure to use relevant tags on your post, only. salesforcedx and salesforcedx-cli don't fit here. – David Reed Jan 8 at 22:20
  • Did you try setting the sorted data to the "data" variable instead of "wiredResult" variable and I think the sort should be against the "data" property on the "wiredResult" variable. wiredResult.data – Craig Austgen Jan 9 at 2:28
0

In your sortData method you are using JSON.parse, returning the results back to the onClickColumnToSort method, then doing an additional this.wiredResult =JSON.parse(JSON.stringify(this.wiredResult)); at the end.

Doing that twice probably won't give you the proper data format for wiredResult

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.