How to create Reusable Datatable in Lightning Web Component(LWC) Salesforce

by Rijwan Mohmmed
4 comments
How-to-create-Reusable-Datatable-in-Lightning-Web-Component(LWC)-Salesforce

Hello Friends , today we will learn how to create a reusable lightning Datatable in LWC. Many time we create Datatable for each object , so instead of this we can create one Datatable and change their objectname and other fields by Design attributes (target Configs ). By target configs we can change variable name when we put our component on page, tab etc.

ReusablecustomListView .Html:

<template>  
      
    <lightning-card title={Title} icon-name={ObjectIcon}>
        <lightning-layout multiple-rows>
            <lightning-layout-item size="6" padding="around-small"></lightning-layout-item>
            <lightning-layout-item size="2" padding="around-small"></lightning-layout-item>
            <lightning-layout-item size="3" padding="around-small">
                <lightning-input type="search" onblur = {handleKeyChange} class="slds-m-bottom_small"
                                variant="label-hidden" placeholder="Search.." label = "Search">
                </lightning-input>
            </lightning-layout-item>
            <lightning-layout-item size="1" padding="around-small">    
                <lightning-button-icon icon-name="utility:refresh"  variant="border-filled" alternative-text="Refresh" title="refresh" onclick={handleRefresh}></lightning-button-icon>
            </lightning-layout-item>
        </lightning-layout>

        <template if:true = {listRecs}>
            <div style="height: 300px;"> 
                <lightning-datatable key-field="Id"  
                                        data={listRecs}  
                                        columns={columns}  
                                        hide-checkbox-column="true"  
                                        show-row-number-column="true"
                                        default-sort-direction={defaultSortDirection}
                                        sorted-direction={sortDirection}
                                        sorted-by={sortedBy}
                                        onsort={onHandleSort}
                                        onrowaction={handleRowAction}>  
                </lightning-datatable>
            </div> 
            <div class="slds-align_absolute-center">
                <lightning-button label="Previous" icon-name="utility:back" onclick={previousHandler} variant="brand" disabled={showButtonPrevious}>
                </lightning-button>
                <span class="slds-badge slds-badge_lightest"
                      style="margin-right: 10px;margin-left: 10px;">
                    Page {page} out of {totalPage}
                </span>
                <lightning-button label="Next" icon-name="utility:forward" icon-position="right"
                        onclick={nextHandler} variant="brand" disabled={showButtonNext}>
                </lightning-button>
            </div>
        </template>
        <template if:true = {error}> 
            {error}
        </template> 
    </lightning-card> 
</template>

ReusablecustomListView .Js

import { api, LightningElement, track, wire } from 'lwc';  
import fetchRecs from '@salesforce/apex/ReusableCustomListViewController.fetchRecs';   
import { NavigationMixin } from 'lightning/navigation';

export default class ReusablecustomListView extends NavigationMixin(LightningElement) {
    listRecs;  
    initialListRecs;
    error;  
    columns;  
    items = []; 
    page = 1; 
    columns; 
    startingRecord = 1;
    endingRecord = 0; 
    pageSize = 10; 
    totalRecountCount = 0;
    totalPage = 0;

    @api Fields;
    @api TableColumns;
    @api Title;
    @api ObjectName;
    @api ObjectIcon = 'standard:account';
    @api RecordPage;

    sortedBy;
    defaultSortDirection = 'asc';
    sortDirection = 'asc';

    connectedCallback() {
        console.log( 'Columns are ' + this.TableColumns );
        this.columns = JSON.parse( this.TableColumns.replace( /([a-zA-Z0-9]+?):/g, '"$1":' ).replace( /'/g, '"' ) );
        console.log( 'Columns are ' + this.columns );
    }

    get vals() { 
        return this.ObjectName + '-' + this.Fields; 
    }

    @wire(fetchRecs, { listValues: '$vals' })  
    wiredRecs( { error, data } ) {

        if(data) {
            this.listRecs = data;
            let newData;   
            let objName = this.RecordPage;
            newData = JSON.parse(JSON.stringify(data));
            newData.forEach(function(entry) {  
                if (entry.CreatedBy){   
                    entry.CreatedByName = entry.CreatedBy.Name;   
                }
                if(entry.Id){
                    entry.recordLink = "/customers/s/" + objName + "?id=" + entry.Id;
                }  
            }); 

            let newRecords = [...newData];   
            this.items = newRecords; 

            this.initialListRecs = this.items;

            this.totalRecountCount = data.length; 
            this.totalPage = Math.ceil(this.totalRecountCount / this.pageSize); 
            this.listRecs = this.items.slice(0,this.pageSize); 
            this.endingRecord = this.pageSize;
        } else if (error) {
            this.listRecs = null;
            this.initialListRecs = null;
            this.error = error;
            console.log(error);
        }
        
    }
    handleRefresh(event){

    }


    //this method displays records page by page
    displayRecordPerPage(page){

        this.startingRecord = ((page -1) * this.pageSize) ;
        this.endingRecord = (this.pageSize * page);

        this.endingRecord = (this.endingRecord > this.totalRecountCount) 
                            ? this.totalRecountCount : this.endingRecord; 

        this.listRecs = this.items.slice(this.startingRecord, this.endingRecord);

        this.startingRecord = this.startingRecord + 1;
    }    


    //clicking on previous button this method will be called
    previousHandler() {
        if (this.page > 1) {
            this.page = this.page - 1; //decrease page by 1
            this.displayRecordPerPage(this.page);
        }
    }

    //clicking on next button this method will be called
    nextHandler() {
        if((this.page<this.totalPage) && this.page !== this.totalPage){
            this.page = this.page + 1; //increase page by 1
            this.displayRecordPerPage(this.page);            
        }             
    }

    get showButtonPrevious(){
        return this.page == 1;
    }

    get showButtonNext(){
        return this.page === this.totalPage;
    }
 
    handleKeyChange(event) {  
          
        const searchKey = event.target.value.toLowerCase();  
        console.log( 'Search Key is ' + searchKey );

        if (searchKey) { 
            this.listRecs = this.initialListRecs;

             if (this.listRecs) {
                let recs = [];
                for ( let rec of this.listRecs ) {

                    console.log( 'Rec is ' + JSON.stringify( rec ) );
                    let valuesArray = Object.values( rec );

 
                    for ( let val of valuesArray ) {
                        if ( (typeof val) != 'object' && val.toLowerCase().includes(searchKey)) {
                            recs.push( rec );
                            break;
                        }
                    }
                }

                console.log( 'Recs are ' + JSON.stringify( recs ) );
                this.items = recs;

             }
 
        }else {
            this.items = this.initialListRecs;
        }

        this.page = 1; 
        this.startingRecord = 1;
        this.endingRecord = 0; 
        this.totalPage = 0;

        this.totalRecountCount = this.items.length; 
        this.totalPage = Math.ceil(this.totalRecountCount / this.pageSize); 
        this.listRecs = this.items.slice(0,this.pageSize); 
        this.endingRecord = this.pageSize;
    }  

    onHandleSort( event ) {
        
        const { fieldName: sortedBy, sortDirection } = event.detail;
        const cloneData = [...this.items];
        cloneData.sort( this.sortBy( sortedBy, sortDirection === 'asc' ? 1 : -1 ) );
        this.items = cloneData;
        this.sortDirection = sortDirection;
        this.sortedBy = sortedBy;

        this.page = 1; 
        this.startingRecord = 1;
        this.endingRecord = 0; 
        this.totalPage = 0;

        this.totalRecountCount = this.items.length; 
        this.totalPage = Math.ceil(this.totalRecountCount / this.pageSize); 
        this.listRecs = this.items.slice(0,this.pageSize); 
        this.endingRecord = this.pageSize;
    }

    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 ) );
        };

    }

    handleRowAction( event ) {

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

    }

    createNew() {

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

    }
}

reusablecustomListView.js-meta.xml :

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
	<apiVersion>51.0</apiVersion>
	<isExposed>true</isExposed>
	<targets>
		<target>lightning__RecordPage</target>
		<target>lightning__HomePage</target>
		<target>lightningCommunity__Page</target>
		<target>lightningCommunity__Default</target>
	</targets>
	 <targetConfigs>
        <targetConfig targets="lightningCommunity__Default, lightning__HomePage">
			<property name="ObjectName" type="String" datasource="Account,Contact,Opportunity,Lead" default="Account"/>
            <property name="Fields" type="String" default="Name, Phone, AccountSource, Rating"/>
            <property name="TableColumns" type="String" default="[{label:'Name', fieldName:'Name', sortable:true}, {label:'Phone',fieldName:'Phone'}, {label:'Account Source',fieldName:'AccountSource'}, {label:'Rating',fieldName:'Rating'},{type:'action',typeAttributes:{rowActions:[{label:'View',name:'view'},{label:'Edit',name:'edit'}]}}]"/>
            <property name="Title" type="String" default="Account List"/>
			<property name="RecordPage" type="String"/>
			<property name="ObjectIcon" type="String" default="standard:account"/>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

ReusableCustomListViewController.cls :

public without sharing class ReusableCustomListViewController {
    @AuraEnabled( cacheable = true )  
    public static List <sObject> fetchRecs(String listValues) {

        List<String> strList = listValues.split( '-' );  
        system.debug( 'values are ' + strList );   
        String strObject = strList.get(0);
        String strFields = strList.get(1);
        
        List <sObject> listRecs = new List < sObject >();
        String strSOQL = 'SELECT Id, ' + strFields + ' FROM ' + strObject;
        
        strSOQL += ' LIMIT 25';
        system.debug( 'SOQL is ' + strSOQL );
        listRecs = Database.query( strSOQL );
        return listRecs;
    } 
}

Now when we add the component we can see the target configs input in right side . See below image

Here you can select object , retrieve fields from apex class, Object icon .

table columns in JSON Format you can change according your requirement

[{label:'Name', fieldName:'Name', sortable:true}, {label:'Phone',fieldName:'Phone'}, {label:'Account Source',fieldName:'AccountSource'}, {label:'Rating',fieldName:'Rating'},{type:'action',typeAttributes:{rowActions:[{label:'View',name:'view'},{label:'Edit',name:'edit'}]}}]

What’s your Reaction?
+1
1
+1
0
+1
0
+1
0
+1
0
+1
0

You may also like

4 comments

Durga June 16, 2022 - 4:37 pm

Hi RIJWAN MOHMMED,

I am struggle with reusable lightning-listview in lightning web component can you help me.

Reply
Rijwan Mohmmed June 20, 2022 - 3:33 pm

Hi Durga,
Can you please more explain about your issue

Reply
SIddhant September 27, 2022 - 11:31 am

When i copy the exact code that you’ve pasted. It gives an error.! And the component is not displayed.

Reply
Rijwan Mohmmed September 27, 2022 - 5:37 pm

Hi SIddhant,
did you go to the page editor and check right hand side config fields, I already show in video please check

Reply

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.