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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
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 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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

1
[{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.

Buy Me A Coffee