September 26, 2020

Sorting in lightning-datatable in LWC Salesforce

Sample Code:

LWC HTML:


<template>
     
    <lightning-card title = "Search Accounts" icon-name = "custom:custom63">
 
        <div class = "slds-m-around_medium">
 
            <lightning-input type = "search" onchange = {handleKeyChange} class = "slds-m-bottom_small" label = "Search" >
            </lightning-input>
 
            <template if:true = {accounts}>
                 
                <div style="height: 300px;">
 
                    <lightning-datatable key-field="Id"
                                         data={accounts}
                                         columns={columns}
                                         hide-checkbox-column="true"
                                         show-row-number-column="true"
                                         onrowaction={handleRowAction}
                                         default-sort-direction={defaultSortDirection}
                                         sorted-direction={sortDirection}
                                         sorted-by={sortedBy}
                                         onsort={onHandleSort}>
                    </lightning-datatable>
 
                </div>                  
     
            </template>
     
            <template if:true = {error}>
 
                {error}>
                 
            </template>
 
        </div>
 
    </lightning-card>
 
</template>

LWC JavaScript:

import { LightningElement, track } from 'lwc';
import fetchAccounts from '@salesforce/apex/AccountController.fetchAccounts';
import { NavigationMixin } from 'lightning/navigation';

const actions = [
    { label: 'View', name: 'view' },
    { label: 'Edit', name: 'edit' },
];
 
const columns = [   
    { label: 'Name', fieldName: 'Name' },
    { label: 'Industry', fieldName: 'Industry', sortable: true },
    {
        type: 'action',
        typeAttributes: { rowActions: actions },
    },
];

export default class Sample extends NavigationMixin( LightningElement ) {
     
    @track accounts;
    @track error;
    @track columns = columns;
    sortedBy;
    defaultSortDirection = 'asc';
    sortDirection = 'asc';
 
    handleKeyChange( event ) {
         
        const searchKey = event.target.value;
 
        if ( searchKey ) {
 
            fetchAccounts( { searchKey } )   
            .then(result => {
 
                this.accounts = result;
 
            })
            .catch(error => {
 
                this.error = error;
 
            });
 
        } else
        this.accounts = undefined;
 
    }

    handleRowAction( event ) {

        const actionName = event.detail.action.name;
        const row = event.detail.row;
        switch ( actionName ) {
            case 'view':
                this[NavigationMixin.Navigate]({
                    type: 'standard__recordPage',
                    attributes: {
                        recordId: row.Id,
                        actionName: 'view'
                    }
                });
                break;
            case 'edit':
                this[NavigationMixin.Navigate]({
                    type: 'standard__recordPage',
                    attributes: {
                        recordId: row.Id,
                        objectApiName: 'Account',
                        actionName: 'edit'
                    }
                });
                break;
            default:
        }

    }
    
    onHandleSort( event ) {

        const { fieldName: sortedBy, sortDirection } = event.detail;
        const cloneData = [...this.accounts];

        cloneData.sort( this.sortBy( sortedBy, sortDirection === 'asc' ? 1 : -1 ) );
        this.accounts = cloneData;
        this.sortDirection = sortDirection;
        this.sortedBy = sortedBy;

    }

    sortBy( field, reverse, primer ) {

        const key = primer
            ? function( x ) {
                  return primer(x[field]);
              }
            : function( x ) {
                  return x[field];
              };

        return function( a, b ) {
            a = key(a);
            b = key(b);
            return reverse * ( ( a > b ) - ( b > a ) );
        };

    }

}

LWC meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
    </targets>
</LightningComponentBundle>

Apex Class:

public with sharing class AccountController {
 
    @AuraEnabled( cacheable = true )
    public static List< Account > fetchAccounts( String searchKey ) {
     
        String strKey = '%' + searchKey + '%';
        return [ SELECT Id, Name, Industry FROM Account WHERE Name LIKE: strKey LIMIT 10 ];
         
    }
     
}

Output:



No comments:

Post a Comment