0

I have a lwc in which I have a lookup field and pick-list field, where lookup field is a child component and pick-list field is standard lightning-input.

Here's the screenshot of the UI:

enter image description here

Problem is, I am only able to select value in the first instance of lookup field, and then I am not able to look up values in any further rows. It does call the methods when I click on the field or type something but does not call apex or search anything.

Here's the .html

<template for:each={itemList} for:item="item" for:index="index">
        <lightning-record-edit-form key={item.id} object-api-name=OpportunityTeamMember onsuccess={handleSuccess} onsubmit={handleSubmit} onerror={handleError}> 
            {item} &nbsp;{index}
            <div class="bodyContainer slds-scrollable">
                <template if:true={showSpinner}>
                    <div class="spinnerContainer">
                        <lightning-spinner alternative-text="Loading..." size="large" variant="brand"></lightning-spinner>
                    </div>
                </template>
                <div class="slds-section slds-is-open slds-m-top_xxx-small slds-m-right_x-small slds-m-left_x-small slds-p-right_x-small slds-p-left_x-small">
                    <div class="slds-section__content">
                        <div class="slds-form slds-form_stacked">
                            <lightning-layout class="slds-wrap" horizontal-align="spread" multiple-rows="true">
                                <lightning-layout-item size="5" class="slds-p-horizontal_xxx-small">
                                    <div key={item.id} class="slds-form-element slds-form-element_edit">
                                        <c-lookup
                                            selection={userSelection}
                                            errors={errors}
                                            onfocus={handleLookupFocus}
                                            onsearch={handleSearch}
                                            onselectionchange={handleSelectionChange}
                                            label="User Id"
                                            placeholder="Search User..."
                                            is-multi-entry={isMultiEntry}
                                            required>
                                        </c-lookup>
                                    </div>
                                </lightning-layout-item>
                                <lightning-layout-item size="5" class="slds-p-horizontal_xxx-small">
                                    <div class="slds-form-element slds-form-element_edit">
                                        <lightning-input-field 
                                                data-inputname="teamRoleField"
                                                field-name="TeamMemberRole"
                                                name="Role"
                                                value={role}
                                                variant="label-stacked"
                                                required
                                                >
                                        </lightning-input-field>
                                        <br/><br/><br/><br/><br/>
                                    </div>
                                </lightning-layout-item>

                                <lightning-layout-item size="2"
                                    padding="around-small">
                                <div>
                                    <lightning-icon class="slds-var-m-around_xx-small" icon-name="action:new" access-key={item.id} id={index}
                                        alternative-text="Add Row" size="small" title="Add Row" onclick={addRow}>
                                    </lightning-icon>
                                    <lightning-icon class="slds-var-m-around_xx-small" icon-name="action:delete" access-key={item.id} id={index}
                                        alternative-text="Delete Row" size="small" title="Delete Row" onclick={removeRow}>
                                    </lightning-icon>
                                </div>
                                </lightning-layout-item>
                            </lightning-layout>
                        </div>
                    </div>
                </div>
            </div>
        </lightning-record-edit-form>
        </template>

.JS

@track itemList = [
        {
            id: 0,
            user:[],
            role:''
        }
    ];

addRow() {
        ++this.keyIndex;
        var newItem = [{ id: this.keyIndex, user:[], role:'' }];
        this.itemList = this.itemList.concat(newItem);
    }

    removeRow(event) {
        if (this.itemList.length >= 2) {
            this.itemList = this.itemList.filter(function (element) {
                return parseInt(element.id) !== parseInt(event.target.accessKey);
            });
        }
    }

    handleLookupFocus(event){
        console.log(' in focus');
        if (event.detail.hasSearchInput) {
            return;
        }
        getRecent()
            .then((results) => {
                this.template.querySelector('c-lookup').setSearchResults(results);
            })
            .catch((error) => {
                this.notifyUser('Lookup Error', 'An error occured while searching with the lookup field.', 'error');
                // eslint-disable-next-line no-console
                this.errors = [error];
            });
    }

    handleSearch(event) {
        console.log('handle search');
        apexSearch(event.detail)
            .then((results) => {
                this.template.querySelector('c-lookup').setSearchResults(results);
            })
            .catch((error) => {
                this.notifyUser('Lookup Error', 'An error occured while searching with the lookup field.', 'error');
                console.error('Lookup search error', JSON.stringify(error));
                this.errors = [error];
            });
    }

    //sets the selection in the Lookup field and the selected user's id
    handleSelectionChange(event){
        this.userSelection = this.template.querySelector('c-lookup').getSelection();
        this.userId = (this.userSelection && this.userSelection.length) ? this.userSelection[0].id : undefined;
    }

How do I Initiate the lookup component again in the new row and get the search result to work?

Here's the JS code in submit() that is throwing error :

this.template.querySelectorAll('c-lookup').forEach(
            element => {
                console.log(' in Lookup element');
                console.log(element);
                isUserEmpty = isUserEmpty && element.reportValidity();
            }
        );

Error thrown : e.reportValidity is not a function I am able to get the lightning-input-field and validate all of them fine but the issue is with c-lookup component.

1

In the code, you have shared. Looks you are using 'querySelector'. querySelector will always return the only first element.

Instead, Add data attribute to each reference of the lookup component. and query specific elements bypassing the data attribute to the querySelector.

Here is a simple example to refer to.

App.html

<template>
    <lightning-layout multiple-rows>
        <lightning-layout-item size="12" padding="around-small">
            <lightning-input label="test1" data-id="1" onchange={handleChange} ></lightning-input>
        </lightning-layout-item>
        <lightning-layout-item size="12" padding="around-small">
            <lightning-input  label="test2" data-id="2" onchange={handleChange}></lightning-input >
        </lightning-layout-item>
        <lightning-layout-item size="12" padding="around-small">
            <lightning-input  label="test3" data-id="3" onchange={handleChange}></lightning-input >
        </lightning-layout-item>
        <lightning-layout-item size="12" padding="around-small">
            <lightning-input  label="test4" data-id="4" onchange={handleChange}></lightning-input >
        </lightning-layout-item>
    </lightning-layout>
</template>

App.js

import { LightningElement, track } from 'lwc';

export default class App extends LightningElement {

    handleChange(event){
      const tar = event.target;
      const id = tar.getAttribute("data-id");
      console.log(id);
      const field = this.template.querySelector(`[data-id="${id}"]`);
      console.log(field.validity.valid); //returns true
    }
}

https://developer.salesforce.com/docs/component-library/tools/playground

4
  • That worked perfectly, I am going to accept it as answer. Thanks a lot. – anxiousAvocado Sep 29 '20 at 4:21
  • @H Reddy, After doing this, my save button that should by default save the values of Lightning edit form, it s not even triggering anything. Anything you can think of? – anxiousAvocado Sep 29 '20 at 4:30
  • @apple123 - please share the code. – Howdy Ranger Sep 29 '20 at 4:41
  • @H Reddy Added the code, I am calling handlesubmit() onclick of the save button but when I try to check the validity of the c-lookup component, I get an error. – anxiousAvocado Sep 29 '20 at 14:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.