LWC: Datatable - way to programmatically handle preselect rows
Shamim siddiquee
Salesforce Enthusiast Developer?? | 2X Certified & Trailhead Ranger ?? | Expert in #Integration & #SalesforceArchitect | Advocate for #LWC, #Apex & #Admin | Experienced in Custom Dev & Data Integration.
Let's try to understand together
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
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?
Finally, we are done, and thanks for reading! Full solution available on git. This process is implemented on the component accountSyncWithOpportunity.
Senior Salesforce Developer | Integration & Automation Expert | 3x Salesforce Certified
3 年This article provided me with some useful insight. Keep up the excellent work!
Salesforce MVP Hall of Fame | 40x Salesforce certified | Kolkata Developer Group Leader | Journey2Salesforce Mentor | Dreamforce Speaker | Blogger
3 年Its nice writing ??
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!