You need to sign in to do that
Don't have an account?
LWC: Datatable - preselect rows programmatically
Hi all,
in the documentation (https://developer.salesforce.com/docs/component-library/bundle/lightning-datatable/documentation) a way is documented to preselect rows programmatically.
For this reason you should use "selected-rows"-attribut on lightning-datatable.
DOCUMENTATION
The selected-rows attribute enables programmatic selection of rows, which is useful when you want to preselect rows.
To select a row programmatically, pass in the row key-field value.
My component looks (simplfied) the following way:
My html-file (simplified) looks the following way:
My purpose: Preselect the current account, because the lwc is placed on a lightning record page for account.
My problem: Nothing happens. No checkbox is active.
One of my first ideas was the key-field. I changed it from "id" (lowercase) to "Id" (uppercase) but that don't solve the problem.
I don't know any other simpler way to test the preselect of rows for datatable than my example above.
Any suggestions?
in the documentation (https://developer.salesforce.com/docs/component-library/bundle/lightning-datatable/documentation) a way is documented to preselect rows programmatically.
For this reason you should use "selected-rows"-attribut on lightning-datatable.
DOCUMENTATION
The selected-rows attribute enables programmatic selection of rows, which is useful when you want to preselect rows.
<lightning-datatable columns={columns} data={data} key-field="id" selected-rows={selectedRows}> </lightning-datatable> <lightning-button label="Select" onclick={handleSelect}> </lightning-button>
To select a row programmatically, pass in the row key-field value.
// Load data via init handler first // then handle programmatic selection handleSelect() { const rows = ['a']; this.selectedRows = rows; }
My component looks (simplfied) the following way:
export default class MergeDuplicates extends LightningElement { @track preSelectedRows = ['0011x00000KOMiJAAX']; [...] }
My html-file (simplified) looks the following way:
<lightning-datatable key-field="Id" data={data} columns={columns} onrowselection={handleSelected} selected-rows={preSelectedRows} is-loading={tableLoadingState}> </lightning-datatable>
My purpose: Preselect the current account, because the lwc is placed on a lightning record page for account.
My problem: Nothing happens. No checkbox is active.
One of my first ideas was the key-field. I changed it from "id" (lowercase) to "Id" (uppercase) but that don't solve the problem.
I don't know any other simpler way to test the preselect of rows for datatable than my example above.
Any suggestions?
Salesforce: Load data via init handler first then handle programmatic selection.
Just don't use a push.
So your code should work if you don't use push anymore on the tracked variable (use a new one like above) and if your record Id is included into the read Ids.
Logically, it is always the 18 characters Id for the both values in your case.
All Answers
There is likely a small javascript error before the selection of the rows.
The code below works in the playground.
https://developer.salesforce.com/docs/component-library/tools/playground
But you try perhaps something more complicated with your merge duplicates?
thanks for your response and sorry for the delay.
Here it is how it looks like (overall):
Any ideas for this behaviour?
From the async connectedCallback (equivalent of the init in Aura ) that still works.
It seems that the push doesn't work but a simpler assignment like below works.
LWC is very capricious and I struggle myself a lot in order to find the right code ( push and sort must be banned for the tracked variables).
Playground:
I will test with a "wire" tonight (not sure that will work for you yet).
thanks for your response.
I try to adopt it in this playground (https://developer.salesforce.com/docs/component-library/tools/playground/SW3lzOCW3/2/edit) and analyze the difference. I can't get it to work. The only(!) difference is that I work with "this.recordId" to add recordId dynamically. Could this be a problem?
There is no usecase to hardcode ids.
Kind regards,
Chris
Salesforce: Load data via init handler first then handle programmatic selection.
Just don't use a push.
So your code should work if you don't use push anymore on the tracked variable (use a new one like above) and if your record Id is included into the read Ids.
Logically, it is always the 18 characters Id for the both values in your case.
thank you so much for your support. I've done it now and it works now.
It looks like the following:
I think I also found the explanation for this behaviour: https://salesforce.stackexchange.com/questions/252996/array-push-wont-update-lightning-web-component-view
Generally the problem is the observation for the pointer and not the object (array) itself.
Difficult to get behind this behavior if it is not so obviously described. If you get to know this behaviour and know about it, you can explain it well. But to get to this point is quite difficult.
Kind regards,
Chris
Interesting and this explanation should exist in the documentation of Salesforce (... somewhere).
Simply, if we just use direct assignation ( = ) without "push" or "sort" on the tracked variable, that should always works for the refresh of LWC.
With Aura Ligthning, we use always explicit updates of the component with: cmp.set('v.field', value); and there are not these subtle distinctions like in LWC.
This problem is disturbed at the beginning because the trace logs show nothing wrong like in your case.
I will see probably many times the same question in the coming months in this forum and this precise explanation will be very useful.
Kind regards,
Alain
This problem is disturbing at the beginning because the trace logs show nothing wrong like in your case.
Thanks again for the link. It is sometimes very time consuming when we search the best explanation.
(sorry for my broken english, if you understood my answer nevertheless that is the most important)
I hope others are still able to get updates to this post.
For some reason this does not work for me at all. Even after following the pattern this.preSelectedRows = [this.preSelectedRowId];
The only difference is that this we have used this as a generic component and being invoked by another parent component. preSelectedRowId is a @api public attribute and I can see both values (preSelectedRows & preSelectedRowId) match on the console. preSelectedRows is a tracked variable.
Any help is highly appreciated!
Raghu
if(result.data) {
this.oppList=result.data.;
this.errorList=undefined;
this.preSelectedRows =["0060K00000baGN5QAM","0060K00000baGN9QAM","0060K00000baGNEQA2"];
}
How to pre popuate sected records Check exampe here (https://www.salesforcepoint.com/2020/07/preselected-checkbox-data-table-Lwc.html)
Java Script code
import { LightningElement,api,wire,track} from 'lwc';
import getAssociatedFacility from '@salesforce/apex/AssignFacilityLWCController.getAssociatedFacility';
import createOpportunuity from '@salesforce/apex/AssignFacilityLWCController.createOpportunuity';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
const columns = [
{ label: 'Facility', fieldName: 'Facility' },
{ label: 'Admission Director', fieldName: 'AdmissionDirector', type: 'text' },
{ label: 'Phone', fieldName: 'Phone', type: 'phone' },
];
export default class AssignFacilityLWCModal extends LightningElement {
@api recordId;
@api accountId;
@api leadName;
@track data;
@track columns = columns;
@track error;
@track preSelectedRows;
@wire(getAssociatedFacility,{sLeadId:'$recordId',sAccountId:'$accountId'})
getAssociatedFacilityWired({ error, data }) {
if (data) {
console.log('data-->',data);
// console.log('data:' + JSON.stringify(data));
let tempRecords = JSON.parse( JSON.stringify( data.assignWrapperList ) );
tempRecords = tempRecords.map( row => {
return { ...row, Facility: row.healthCenter.Signature_Healthcare_Center__r.Facility_Short_Name__c,
AdmissionDirector: row.healthCenter.Signature_Healthcare_Center__r.Admission_Director__r.Name,
Phone: row.healthCenter.Signature_Healthcare_Center__r.Phone__c };
});
this.data = tempRecords;
this.preSelectedRows = data.selectedIdSet; // data.selectedIdset alreasy set in apext controller
//this.preSelectedRows = ["a1d7A000000jZJhQAM"];
console.log('this.preSelectedRows length2-->',this.preSelectedRows.length); // it prints 1
console.log('this.preSelectedRows-->',this.preSelectedRows);
// this.data = data;
console.log(' this.data-->', this.data);
this.error = undefined;
} else if (error) {
this.error = error;
this.data = undefined;
}
}
}
Apex Controller
@AuraEnabled(cacheable=true)
public static AssignFacilityListWrapper getAssociatedFacility(Id sLeadId,Id sAccountId){
List<AssignFacilityWrapper> assignFacilitywrapperList = new List<AssignFacilityWrapper>();
AssignFacilityListWrapper listWrapObj = new AssignFacilityListWrapper();
AssignFacilityWrapper assignFacilityWrap;
set<Id> setOfFacilityIds = new set<Id>();
map<Id,Opportunity> map_FacilityId_oppy = new map<Id,Opportunity>();
for(Opportunity oppy :[select id,Facility__c from Opportunity where Lead__c = :sLeadId]){
map_FacilityId_oppy.put(oppy.Facility__c,oppy);
}
for(Associated_Healthcare_Center__c healthCenter: [SELECT id,Signature_Healthcare_Center__c,Signature_Healthcare_Center__r.phone__c,
Signature_Healthcare_Center__r.Facility_Short_Name__c,
Signature_Healthcare_Center__r.Admission_Director__r.Name
FROM Associated_Healthcare_Center__c
WHERE Account__c =:sAccountId
Order By Signature_Healthcare_Center__r.Facility_Short_Name__c]){
assignFacilityWrap = new AssignFacilityWrapper();
assignFacilityWrap.healthCenter = healthCenter;
if(map_FacilityId_oppy !=null && map_FacilityId_oppy.containsKey(healthCenter.Signature_Healthcare_Center__c)){
assignFacilityWrap.isSelected = true;
setOfFacilityIds.add(healthCenter.Signature_Healthcare_Center__c);
}
assignFacilitywrapperList.add(assignFacilityWrap);
}
listWrapObj.assignWrapperList = assignFacilitywrapperList;
listWrapObj.selectedIdSet = setOfFacilityIds;
system.debug('listWrapObj---'+listWrapObj);
//return assignFacilitywrapperList;
return listWrapObj;
}
public class AssignFacilityWrapper{
@AuraEnabled public boolean isSelected{get;set;}
@AuraEnabled public boolean isExisting{get;set;}
@AuraEnabled public Associated_Healthcare_Center__c healthCenter{get;set;}
public AssignFacilityWrapper(){
isSelected = false;
isExisting = false;
}
}
public class AssignFacilityListWrapper{
@AuraEnabled public List<AssignFacilityWrapper> assignWrapperList{get;set;}
@AuraEnabled public set<Id> selectedIdSet {get; set;}
AssignFacilityListWrapper(){}
}
Template code
<div style="height: 300px;">
<lightning-datatable
key-field="Signature_Healthcare_Center__c"
data={data}
columns={columns}
selected-rows={preSelectedRows}>
</lightning-datatable>
</div>
I am fyring to get the prechecked rows. I am getting the IDs which I pass into selected-rows but it isn't working. Below is my code: