LWC: Datatable - way to programmatically handle preselect rows

LWC: Datatable - way to programmatically handle preselect rows

Let's try to understand together

  1. Create new components.
  2. Used @wire and imperative process to Load data.
  3. Helps to understand how to use @api for a parent-child component to configure data-table columns, data sources.
  4. Child component with an LWC: Datatable.
  5. Configure Parent component HTML Attribute to show/hide child component data-table checkbox.
  6. Configure Parent component HTML Attribute to show/hide child component data-table column border.
  7. From parent component how to select child component event.
  8. On the parent component how to select child component by tag and id.?

Recently I am working on?LWC: Datatable. I need to show large data in tabular format. Large data will not load at a time, so need to use pagination. The table also has flexibility, a user can select records as per need. The selected records can process for the next step.

So, need to persist all selected rows. After configuring/selecting a page record. The user may view other pages also he may back to his configured page, the page should exist configured records.

Use case

The client has a requirement, want to see the retrieved records from the database in tabular view with pagination. There should have the functionality to preserve selected records.

Solution Approach

We know lightning data-table easily helps us to show large data in tabular format, with a flexible selection approach.

When pagination applies with the LWC: Datatable pre-selected-rows, it does not work straightforward way. Because apply pagination helps to display only selected page information and hide the rest of the records actually they are not populated yet.

So when you want to know about the selected rows from the data table, it gives you results in only the current page information not persist the previous or next page configured selected records.

To resolve the selection issue, we need to store the selected records page-wise.?

When the user selects any page, the storage helps to populate his previous selected options. If he has done any new selection update. The system will also update the storage with the newly selected option.

Flow diagram

Flow diagram

This HTML contains component c-reusable-data-table-with-preselect.Here configuring the attributes user can configure the data table, like column-boarder and hide-checkbox with the value true and false.

<c-reusable-data-table-with-preselect
? ? ? ? ? ? data-id="accountSyncGrid"
? ? ? ? ? ? card-title="Account list"
? ? ? ? ? ? source-data={accountData}
? ? ? ? ? ? columns={accountColumns}
? ? ? ? ? ? column-boarder="true"
? ? ? ? ? ? hide-checkbox="false"
? ? ? ? ? >
</c-reusable-data-table-with-preselect>        

Button click event help to get child component data table selected rows.

<lightning-button-icon
????????icon-name="utility:sync"
????????variant="border-filled"
????????alternative-text="Sync?Acc?with?Opp"
????????slot="actions"
????????onclick={handleSync}
??????>
</lightning-button-icon>


handleSync()?{
????this.processing?=?true;

// Base on component Id, get child components selected records

????let?selectedRows?=?this.template
??????.querySelector('[data-id="accountSyncGrid"]')
??????.getRows();


????syncLatestOpportunityWithAccounts({?accounts:?selectedRows?})
??????.then((response)?=>?{
????????if?(response?===?"Success")?{
??????????this.showToastMessage(
????????????"success",
????????????`With?success,total?sync?${selectedRows.length}?records.`
??????????);
????????}?else?{
??????????this.showToastMessage("error",?`With?errors?reason?for?${response}`);
????????}
??????})
??????.catch((error)?=>?{
????????console.log(error.body.message);
??????})
??????.finally(()?=>?{
????????//this.processing?=?false;
????????this.handleLoadAccountRelatedLatestOpportunity();
??????});
??}
        

This HTML contains component reusableDataTableWithPreselect it used lightning data table. Here users can configure almost every attribute from a parent component.

?
?????<lightning-datatable
????????class={columnBoarderClass}
????????key-field="id"
????????data={data}
????????onrowaction={handleRowAction}
????????show-row-number-column
????????row-number-offset={rowOffset}
????????hide-checkbox-column={isHideChkColumn}
????????columns={columns}
????????selected-rows={prePageSelectedRows}
????????onrowselection={handleRowSelection}
??????>
??????</lightning-datatable>        

JS events help to persist selected options?

getPrePageSelectedRows(page) {
	try {
		let selectedRowsMap = this.data.map((item) => item.id);
		if (!this.isNotBlank(this.selectedRowsPagesMap[page])) {
			this.selectedRowsPagesMap[page] = selectedRowsMap;
		}

		this.prePageSelectedRows = this.selectedRowsPagesMap[page];

		this.getTotalSeletedRows();

		this._originTagRowSelectionLocal = "button";
	} catch (error) {
		console.log(error);
	}
}


handleRowSelection(event) {
	try {
		if (this._originTagRowSelectionLocal === "LIGHTNING-DATATABLE") {
			let selectedRowsMap = event.target.selectedRows;

			//unselected rows store page-wise.
			let unSelectedRowsMap = 
                    this.prePageSelectedRows.filter((item) =>
                    !selectedRowsMap.includes(item));
			this.unSelectedRowsPagesMap[this.page] = unSelectedRowsMap;

			//selected rows store page-wise.
			this.selectedRowsPagesMap[this.page] = [...selectedRowsMap];

			this.getTotalSeletedRows();


			this._originTagRowSelectionLocal = event.target.tagName;
		} else {
			this._originTagRowSelectionLocal = event.target.tagName;
		}
	} catch (error) {
		console.log(error);
	}
}


getTotalSeletedRows() {
	try {
		let totalCounter = 0;
		Object.values(this.selectedRowsPagesMap).forEach((rowsList) => {
			totalCounter += this.pageSize - rowsList.length;
		});


		this.allSeletedRowCount = this.totalRecountCount - totalCounter;
	} catch (error) {
		console.log(error);
	}
}        

Final Outcome

LWC: Datatable - programmatically handle preselect rows?

LWC: Datatable - programmatically handle preselect rows

Finally, we are done, and thanks for reading! Full solution available on git. This process is implemented on the component accountSyncWithOpportunity.

Ridowan Ahmed

Senior Salesforce Developer | Integration & Automation Expert | 3x Salesforce Certified

3 年

This article provided me with some useful insight. Keep up the excellent work!

回复
Santanu Boral, ?

Salesforce MVP Hall of Fame | 40x Salesforce certified | Kolkata Developer Group Leader | Journey2Salesforce Mentor | Dreamforce Speaker | Blogger

3 年

Its nice writing ??

回复
Gaurav Kheterpal

Founder & CEO - Vanshiv Technologies, Instructor, Multi-Cloud Enterprise Architect, Salesforce MVP Hall of Fame, Mulesoft Ambassador, GDG Cloud Leader, GenAI Enthusiast, 18+ Years on Salesforce

3 年

Great post shamim - keep sharing your knowledge!

要查看或添加评论,请登录

Shamim siddiquee的更多文章

社区洞察

其他会员也浏览了