Keep Selected Rows in LWC Datatable Pagination

by Rijwan Mohmmed
keep-selected-rows-in-lwc-datatable-pagination

Hello folks, today we will discuss the Keep Selected Rows in LWC Datatable Pagination. Here we can keep selected records by paginating the data. So if we go on the same page again by pagination we can see selected records. Pagination is used for displaying large amounts of data in chunks. Using pagination we can control the number of records displayed on each page.

Also, check this: Queueable Apex In Salesforce

keep-selected-rows-in-lwc-datatable-pagination-output-techdicer

Key Highlights :

  1. Persistent selected rows.
  2. After pagination, multiple pages still get selected records.
  3. Show extensive data in the table

Code :

DataController.cls :

public with sharing class DataController {
    @AuraEnabled (cacheable=true)
    public static List<Account> retrieveAccounts(){
        return [SELECT Id, Name, Type, BillingCountry, Industry, Email__c
                FROM Account
                LIMIT 2000];
    }
}

selectedRowsPersistentPaginationLWC.HTML :

<template>
	<lightning-card title="Selected Rows Persistent Pagination LWC Datatable" icon-name="standard:contact">
		<!-- Datatable with Pagination End -->
		<div class="slds-m-around_medium">
			<div>
				<lightning-datatable data-id="datatable" key-field="Id" data={data} columns={columns} selected-rows={selectedRows}
					onrowselection={handleRowSelection}>
				</lightning-datatable>
			</div>
		</div>

		<!--  Pagination Buttons Start -->
		<div class="slds-align_absolute-center">
			<lightning-button label="Previous" icon-name="utility:chevronleft" onclick={previousHandler}
				disabled={isPreviousDisable}>
			</lightning-button>

			<span class="slds-badge slds-badge_lightest"
                        style="margin-right: 10px;margin-left: 10px;">
                       Displaying {startingRecord} to {endingRecord} of {totalRecountCount} records.
                     Page {page} of {totalPage}.
            </span>

			<lightning-button label="Next" icon-name="utility:chevronright" icon-position="right" onclick={nextHandler}
				disabled={isNextDisable}>
			</lightning-button>
		</div>
		<!--  Pagination Buttons End -->
		<!-- Datatable with Pagination End -->
	</lightning-card>
</template>

selectedRowsPersistentPaginationLWC.JS:

import { LightningElement, wire } from 'lwc';
import retrieveAccounts from '@salesforce/apex/DataController.retrieveAccounts';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
const columns = [
    { label: 'Name', fieldName: 'Name' },
    { label: 'Type', fieldName: 'Type' },
    { label: 'Industry', fieldName: 'Industry' },
    { label: 'BillingCountry', fieldName: 'BillingCountry' },
];

export default class SelectedRowsPersistentPaginationLWC extends LightningElement {
    page = 1; //initialize 1st page
    items = []; //contains all the records.
    data = []; //data  displayed in the table
    columns; //holds column info.
    startingRecord = 1; //start record position per page
    endingRecord = 0; //end record position per page
    pageSize = 10; //default value we are assigning
    totalRecountCount = 0; //total record count received from all retrieved records
    totalPage = 0; //total number of page is needed to display all records
    selectedRows = [];

    @wire(retrieveAccounts)
    wiredAccounts({ error, data }) {
        if (data) {
            this.items = data;
            this.totalRecountCount = data.length;
            this.totalPage = Math.ceil(this.totalRecountCount / this.pageSize);
            //here we slice the data according page size
            this.data = this.items.slice(0, this.pageSize);
            this.endingRecord = this.pageSize;
            this.columns = columns;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.data = undefined;
            this.showToast(this.error, 'Error', 'Error'); //show toast for error
        }
    }

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

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

    //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.data = this.items.slice(this.startingRecord, this.endingRecord);

        //increment by 1 to display the startingRecord count, 
        //so for 2nd page, it will show "Displaying 6 to 10 of 23 records. Page 2 of 5"
        this.startingRecord = this.startingRecord + 1;
        this.template.querySelector('[data-id="datatable"]').selectedRows = this.selectedRows;
    }

    handleRowSelection(event) {
        let updatedItemsSet = new Set();
        // List of selected items we maintain.
        let selectedItemsSet = new Set(this.selectedRows);
        // List of items currently loaded for the current view.
        let loadedItemsSet = new Set();

        this.data.map((ele) => {
            loadedItemsSet.add(ele.Id);
        });

        if (event.detail.selectedRows) {
            event.detail.selectedRows.map((ele) => {
                updatedItemsSet.add(ele.Id);
            });

            // Add any new items to the selectedRows list
            updatedItemsSet.forEach((id) => {
                if (!selectedItemsSet.has(id)) {
                    selectedItemsSet.add(id);
                }
            });
        }

        loadedItemsSet.forEach((id) => {
            if (selectedItemsSet.has(id) && !updatedItemsSet.has(id)) {
                // Remove any items that were unselected.
                selectedItemsSet.delete(id);
            }
        });

        this.selectedRows = [...selectedItemsSet];
        console.log('selectedRows==> ' + JSON.stringify(this.selectedRows));
    }

    showToast(message, variant, title) {
        const event = new ShowToastEvent({
            title: title,
            message: message,
            variant: variant,
            mode: 'dismissable'
        });
        this.dispatchEvent(event);
    }
}

selectedRowsPersistentPaginationLWC.js-meta.xml:

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
	<apiVersion>55.0</apiVersion>
	<isExposed>true</isExposed>
	<targets>
		<target>lightning__HomePage</target>
	</targets>
</LightningComponentBundle>

Output :

keep-selected-rows-in-lwc-datatable-pagination-output-techdicer
keep-selected-rows-in-datatable-pagination-output-techdicer

Reference :

  1. LWC Datatable
What’s your Reaction?
+1
2
+1
0
+1
0
+1
0
+1
0
+1
0

You may also like

Leave a Comment