0

I want to display empty lookup in my child component when button clicks on parent component.

Basically the idea is to refresh the child comp when I click on save button in parent component. I tried out multiple ways to refresh the child comp nothing was working. So, i tried passing a variable (flagfromChild) from parent to child when save button is clicked.

I have written show-null={flagfromChild} in parent code. Its working for the first time only (on page refresh), second time I could see that variable shownull is set to true in console log but it displays <template if:false={showNull}> block instead of <template if:true={showNull}>.

parent.html

<template>
    <lightning-card title="Create a Task">           
        <div class="slds-box">
            <lightning-input type="text" label="Subject" value={taskSubject} onchange={handleSubject}></lightning-input>
        </br>
            <template if:true={PriorityValues.data}>
                <lightning-combobox name="progress" label="Priority" value={taskPriority}
                    options={PriorityValues.data.values} onchange={handleChange}>
                </lightning-combobox>
            </template>
            <template if:true={StatusValues.data}>
                <lightning-combobox name="progress" label="Status" value={taskStatus}
                    options={StatusValues.data.values} onchange={handleStatusChange}>
                </lightning-combobox>
            </template>
        </br>       
            <c-account-Lookup label="Related To" onselected={HandleLookup} show-null={flagfromChild} ></c-account-Lookup>
             <div slot="footer">
                <lightning-button label="Submit" onclick={saveAccountAction} variant="brand"></lightning-button>
              </div>
        </div>     
    </lightning-card>
</template>

parent.js

import { LightningElement,wire,track } from 'lwc';
import { createRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import TASK_OBJECT from '@salesforce/schema/Task';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import Priority from '@salesforce/schema/Task.Priority';
import Status from '@salesforce/schema/Task.Status';
import Subject from '@salesforce/schema/Task.Subject';
import WhatId from '@salesforce/schema/Task.WhatId';
import OwnerId from '@salesforce/schema/Task.OwnerId';
import userId from '@salesforce/user/Id';

export default class CreateTaskforMultipleObjs extends LightningElement {
    
    @track assignedto = userId;
    @track taskSubject;
    @track taskPriority;
    @track taskStatus;
    @track selectedAccId;
    @track taskId;    
    @track flagfromChild = false;

    @wire(getObjectInfo, { objectApiName: TASK_OBJECT})
    TaskInfo;

    @wire(getPicklistValues,
        {
            recordTypeId: '012000000000000AAA',
            fieldApiName: Priority
        }
    )
    PriorityValues;
    @wire(getPicklistValues,
        {
            recordTypeId: '012000000000000AAA',
            fieldApiName: Status
        }
    )    
    StatusValues;
    handleChange(event)
    {
        this.taskPriority = event.target.value;
        console.log('Selected Priority is',this.taskPriority);
    }
    handleStatusChange(event) 
    { 
        this.taskStatus = event.target.value;
        console.log('Selected Status is',this.taskStatus);
    }
    handleSubject(event)
    { 
      this.taskSubject = event.target.value;
      console.log('Subject is', this.taskSubject);      
      
    }
    HandleLookup(event){
        console.log('Child in Parent',event.detail);
        this.selectedAccId = event.detail;
    }
       saveAccountAction(event){
        this.flagfromChild = false;
        console.log('Flag from child at start',this.flagfromChild); 
        console.log('Selected Account',this.selectedAccId);  
        const fields = {};       
        fields[Subject.fieldApiName] = this.taskSubject;
        fields[Priority.fieldApiName] = this.taskPriority;
        fields[Status.fieldApiName] = this.taskStatus;
        fields[OwnerId.fieldApiName] = this.assignedto;                
       fields[WhatId.fieldApiName] = this.selectedAccId;
        const recordInput = { apiName: TASK_OBJECT.objectApiName, fields };

        createRecord(recordInput)
            .then(taskobj=> {
                this.taskId = taskobj.id;
                this.fields={};
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Task created successfully..!',
                        variant: 'success',
                    }),
                );
                })
            .catch(error => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,
                        variant: 'error',
                    }),
                );
            });
         //reset the values
         console.log('Reset the values');
        this.taskSubject = '';   
        this.flagfromChild = true;   
        console.log('Flag from child',this.flagfromChild);              
        
    }    
}

child.html

<template>
    <lightning-card title="Child Lookup">
        <template if:false={showNull}>
    <div class="slds-combobox__form-element slds-input-has-icon slds-input-has-icon_right"
    role="none">
    <lightning-input type="search" id="combobox-id-16" value={accountName}
        onchange={searchHandleKeyChange} onkeydown={searchHandleClick} onclick={searchHandleClick}
        onblur={searchHandleClick} aria-activedescendant="option1" label='Account'
        aria-autocomplete="list" aria-controls="listbox-id-12" role="textbox"
        placeholder="Search..."></lightning-input>   
</div>
        </template>
<template if:true={showNull}>
    <div class="slds-combobox__form-element slds-input-has-icon slds-input-has-icon_right"
    role="none">
    <lightning-input type="search" id="combobox-id-17"  onclick={searchHandleClick1}
        aria-activedescendant="option1" label='Account'
        aria-autocomplete="list" aria-controls="listbox-id-12" role="textbox"
        placeholder="Search..."></lightning-input>   
</div>
</template>

   <div if:true={messageResult}>
       No result found
   </div>
   <div if:false={messageResult}>    
</div>

<template if:true={showSearchedValues}>
<ul>
    <template for:each={accList} for:item="acc">
        <li key={acc.Id} onclick={parentHandleAction} data-value={acc.Id} data-label={acc.Name}>
            {acc.Name}
        </li>
    </template>
</ul>

</template>
</lightning-card>
</template>

child.js

import { LightningElement,track,wire,api } from 'lwc';
import getAccs from '@salesforce/apex/AccountLookup.getAccount';

export default class AccountLookup extends LightningElement {

    @track accountName = '';
    @track accountId;
    @track messageResult = false; //displays msg when no data found
    @track showSearchedValues = false; //decides to display searched accounts
    @track accList = []; //store Accounts
    @track isShowResult = true; //display accounts on below searchbar
    @api showNull; //to control visibility in parent
   

    //wire method to get Account names

    @wire(getAccs, {accName : '$accountName'})
    retrieveAccs({data,error}){
        this.messageResult=false;
        if(data){             
            if(data.length > 0 && this.isShowResult)
            {
             console.log('Data length1', data.length)
              this.accList = data;
              this.showSearchedValues = true;
              this.messageResult = false;
            }
            else if(data.length == 0)
            { 
                this.accList = [];
                this.showSearchedValues = false;
                if(this.accountName != '')
                {
                this.messageResult = true;
                }
            }
            else if (error)
            { 
                this.accountId = '';
                this.accountName = '';
                this.accList = [];
                this.showSearchedValues = false;
                this.messageResult = true;
            }
        }
    }
    searchHandleClick1(event)
    { 
        this.accountName = '';
        this.showNull = false;
    }
    searchHandleKeyChange(event)
    {
    console.log('Inside getting account name');
     this.messageResult=false;     
     this.accountName = event.target.value;
          
    }
    searchHandleClick(event)
    {
        this.isShowResult = true;
        this.messageResult = false;
      }
    
    parentHandleAction(event)
    { 
        console.log('Null pointer',this.showNull);
        console.log('Specific value selected');
        this.showSearchedValues = false;
       this.isShowResult = false;
       this.accountId = event.target.dataset.value;       
       this.accountName = event.target.dataset.label;
       console.log('Account id',this.accountId);
       const selectedEvent = new CustomEvent('selected', {detail : this.accountId});
       this.dispatchEvent(selectedEvent);       
       
    }
}    
1
  • You've been here for a while now. Please learn how to properly format your questions yourself. See the editing help page.
    – Derek F
    Mar 16 at 14:50

1 Answer 1

0

As I under it you have a seach input (lookup) in your child component, which gets the list of accounts. And your objective is to clear the values given to this input.

You could try clearing the value attribute of the input i.e

this.accountName = ''

As opposed to rendering two different input elements.

Also I notice that you are using

Task Object with lightning/uiRecordApi

which is not supported.

What you could do is, since your action is in parent, in parent while clicking the submit button, you could call a method accountName in child.

So your updated segments of code would look like below:

parent.js

saveAccountAction(event){
   
   const objChild = this.template.querySelector('accountLookup');
   objChild.resetAccountName();
   //Rest of the code as is
}

child.js

resetAccountName(){
  this.accountName = '';
}
8
  • what you have understood is correct, am not sure at which place i have to set this.accountName = '' so that it will show no value in lookup field on after clicking save from Parent. Task Object with lightning/uiRecordApi - yes you're correct(which will be handled using apex) but the aim of the logic is to refresh child comp or show no value on the lookup when clicking on 'Save' from parent
    – Sumo sales
    Mar 17 at 13:30
  • @Sumosales I have updated my answer to show how/where you could refresh he accountName Mar 18 at 10:19
  • Thanks much for your reply. I have added the code you have provided to my code but its not working. Parent.html <c-account-Lookup label="Related To" onselected={HandleLookup}></c-account-Lookup> parent.js SaveAccountAction(event){ console.log('Inside submit'); const objChild = this.template.querySelector('child'); objChild.resetAccountName(); console.log('Selected Account',this.selectedAccId); rest of the code as is
    – Sumo sales
    Mar 21 at 8:31
  • in console log, 'inside submit' is logging after that code is not working (parent-child comp communication is not working) it seems as 'selected acccount' is not displayed in console also, the console log not logged the debug statement which i have written in resetAccountname(). fyr, i have added my html code to know did i miss something in parent html.
    – Sumo sales
    Mar 21 at 8:31
  • @Sumosales your child component is 'accountLookup' , correct? So the code should be: const objChild = this.template.querySelector('accountLookup'); Could you please try this and let me know? Mar 21 at 8:47

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.