pozil/sfdc-ui-lookup-lwc

When the component is used more than once, the lookup.setDefaultResults call doesn't work

stephenpstanley opened this issue · 5 comments

I've managed to get the first instance of the call to work by making the following changes as when running synchronously, the call to querySelector was returning null, but I think you may need to use a querySelectorAll if the component is used more then one within a parent component. I'm not sure I'm skilled enough to sort this out, but will give it a try and let you know

async initLookupDefaultResults() {
    // Allow the DOM to update.
    await Promise.resolve();
    // Make sure that the lookup is present and if so, set its default results
    const lookup = this.template.querySelector('c-lookup');
    if (lookup) {
        console.log('Calling setDefaultResults');
        lookup.setDefaultResults(this.recentlyViewed);
    }
}
pozil commented

Hi @stephenpstanley, yes, the provided example only works for a single lookup because of the way CSS selectors work.
You'll likely need distinct default values if you have several lookups. Instead of using a c-lookup tag selector which is common to all lookup instances, you can use CSS class selectors like .myLookup1, .myLookup2...

pozil commented

It does work like this. You probably missed something in your code.
For example you can modify the sample lookup app to introduce a second lookup with specific focus controls:

<c-lookup
    class="myLookup1"
    selection={initialSelection}
    errors={errors}
    onsearch={handleLookupSearch}
    onselectionchange={handleLookupSelectionChange}
    label="Search"
    placeholder="Search Salesforce"
    is-multi-entry={isMultiEntry}
    new-record-options={newRecordOptions}
    required
>
</c-lookup>

<c-lookup
    class="myLookup2"
    selection={initialSelection}
    errors={errors}
    onsearch={handleLookupSearch}
    onselectionchange={handleLookupSelectionChange}
    label="Search"
    placeholder="Search Salesforce"
    is-multi-entry={isMultiEntry}
    new-record-options={newRecordOptions}
    required
>
</c-lookup>

<div class="slds-var-m-top_large">
    <lightning-button label="Focus 1" onclick={handleFocus1}></lightning-button>&nbsp;
    <lightning-button label="Focus 2" onclick={handleFocus2}></lightning-button>&nbsp;
    <lightning-button label="Clear" onclick={handleClear}></lightning-button>&nbsp;
    <lightning-button variant="brand" label="Submit" onclick={handleSubmit}></lightning-button>
</div>
handleFocus1() {
   this.template.querySelector('.myLookup1').focus();
}

handleFocus2() {
    this.template.querySelector('.myLookup2').focus();
}
pozil commented

If you want to share a handler, you can retrieve the value of a dataset attribute like this is done here:
https://github.com/pozil/sfdc-ui-lookup-lwc#passing-custom-data-to-javascript-and-apex-optional