Thursday, April 16, 2020

Custom data table with onload custom sorting in lightning web components(lwc)

This post explains the custom data table with onload custom sorting in lightning web components(lwc)

In some scenarios, we need to sort the data based on the particular field when table loading the data.

For Demo, I used the opportunity data and sort the data based on the amount field when table loading the data.

HTML Code
<template>
    <div if:true={oppData}>
        <table class="slds-table slds-cell-wrap">
            <thead>
                <tr class="slds-line-height_reset">
                    <th scope="col" data-id="Opportunity Name">
                        <b>Opportunity Name</b>
                    </th>

                    <th scope="col" data-id="Stage Name">
                        <b>Stage Name</b>
                    </th>
                    <th scope="col" data-id="Amount">
                        <b>Amount</b>
                    </th>
                </tr>
            </thead>
            <tbody>
                <template for:each={oppData} for:item="keyValue">
                    <tr key={keyValue.Id}>
                        <td>
                            <a href={oppURL} target="_blank" data-id={keyValue.Id} onclick={gotoOpp}>{keyValue.Name}</a>
                        </td>
                        <td>
                            {keyValue.StageName}
                        </td>
                        <td>
                            {keyValue.Amount}
                        </td>
                    </tr>
                </template>
            </tbody>
        </table>
    </div>
</template>

JS Controller
import {
    LightningElement,
    wire
} from 'lwc';
import opps from "@salesforce/apex/GenericController.returnOpps";

export default class OnloadSorting extends LightningElement {
    oppData = [];
    oppURL;

    @wire(opps)
    opp({
        error,
        data
    }) {
        if (data) {
            console.log('data ===> ' + JSON.stringify(data));
            this.oppData = JSON.parse(JSON.stringify(data)).sort((a, b) => {

                Object.keys(a).map((key) => {
                    if (key == 'Amount') {
                        a = a[key];
                    }
                });

                Object.keys(b).map((key) => {
                    if (key == 'Amount') {
                        b = b[key];
                    }
                });

                return -1 * ((a > b) - (b > a));

            });
        } else if (error) {
            console.log(error);
        }
    }

    gotoOpp(event) {
        this.oppURL = window.location.origin + "/" + event.currentTarget.dataset.id;
    }
}

Apex Class
public inherited sharing class GenericController {
    @AuraEnabled(Cacheable=true)
    public static list<Opportunity> returnOpps(){
        return [SELECT Id, Name, StageName, Amount FROM Opportunity WHERE amount != null limit 10];
    }
}

Output

No comments:

Post a Comment