function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Nandhini S 3Nandhini S 3 

Help with lightning web component

Hi,
I'm building a lightning web component which should display result based on search result and display all the accounts when i clear the search box.
My component is displaying the search records correctly but when i clear the search box no records are displayed in the table.
User-added image
JS
*********
import { LightningElement,wire } from 'lwc';
import getAccount from '@salesforce/apex/searchLWC.getAccount';
export default class AccountSearch extends LightningElement {
    
    columns = [
      
        {
            label: 'Account Name',
            fieldName: 'Name',
            type: 'text',
        },
        {
            label: 'Account Type',
            fieldName: 'Type',
            type: 'Text',
        }
    ];
    //error;
    //accList;
    
    @wire(getAccount)
    wiredAccounts;
    /*({
        error,
        data
    }) {
        if (data) {
            this.accList = data;
        } else if (error) {
            this.error = error;
        }
    }*/
  
    
    buttonLabel ='Show Table';
    showTable;
    handleClick(){
        if(this.buttonLabel==='Show Table')
        {
            this.buttonLabel='Hide Table';
            this.showTable=true;
        }
        else
        {
            this.showTable=false;
            this.buttonLabel='Show Table';
        }
    }
     //data= wiredAccounts.data;
    searchWord;
    handleKeyUp(event){
        var keyWord=event.target.value;
        var recs= this.wiredAccounts.data;
        
       this.wiredAccounts.data=[];
       
        if(keyWord !='')
        {
            for(let i=0;i<recs.length;i++)
            {
                if(recs[i].Name.toLowerCase().includes(keyWord.toLowerCase()))
                {
                    this.wiredAccounts.data = [...this.wiredAccounts.data,recs[i]];
                }
            }
        }
            else
            {
                this.wiredAccounts.data=this.wiredAccounts.data;
            }
        
    }
}


HTML
**********
<template>
    <div onkeyup={handleKeyUp}>
        <lightning-input
            name="enter-search"
            label="Search using Name"
            type="search"
        ></lightning-input>
        </div>
    <lightning-button variant="brand" label={buttonLabel} title="Show/Hide data" onclick={handleClick} class="slds-m-left_x-small">
    </lightning-button>
    
<template if:true={showTable}>
    <div style="height: 300px;">
        <lightning-datatable
                key-field="id"
                data={wiredAccounts.data}
                columns={columns}
                hide-checkbox-column>
        </lightning-datatable>
    
    </div> 
</template>   
</template>
ANUTEJANUTEJ (Salesforce Developers) 
Hi Nandhini,

As mentioned in the link https://salesforce.stackexchange.com/questions/252323/how-do-you-change-the-value-of-a-lightning-input-field-in-javascript this seems to be the expected behaviour for further understanding you can try checking the best answer as it mentioned about the explanation of why this is not possible.

I am attaching the below text that is present in the link for quick reference:

If a user enters anything in an input field, you can no longer programmatically set the value of the field. The assumption is that there are unsaved changes that should not be overwritten. If you want to be able to overwrite user changes, you can use lightning-input instead.

Additionally, I would also suggest you to try checking the idea in the below link and upvote so that it may be considered in the future if it reaches the necessary threshold votes.

Let me know in case if there are any issues.

Regards,
Anutej
ANUTEJANUTEJ (Salesforce Developers) 
There is also a workaround that is mentioned that you could try.
Nandhini S 3Nandhini S 3
Hi Anutej,

Thanks for replying.

In my component, when i give a text in the search box, it should display the accounts containing the same name. When i clear the searchbox, it should display all the account list.
But when i clear the searchbox, it doesn't display anything in the data table.
how can i display the intial list of data that was fetched from the apex class,when the searchbox  = null?

Apex class: (missed to add it earlier)
public class searchLWC {
    @auraenabled(cacheable=true)
    public static List<account> getAccount()
    {
        List<account> acc = [select name,type from account limit 5];
        return acc;
    }

}
ANUTEJANUTEJ (Salesforce Developers) 
Hi Nandhini,

I tried a different code and I was able to get the results but to show the list of records when the search text is empty you need to click on search. Please try checking the below code:
 
APEX Class:

public with sharing class customSearchController {

    @AuraEnabled(cacheable=true)
    public static List<contact> allContacts() {
        return [Select id,Name,Email,FirstName,LastName,Phone
        From Contact];
    }
  
    @AuraEnabled(cacheable=true)
     public static list<contact> getContactList(string searchKey) {
         string sTempSearchKey = '%' + searchKey + '%';
         
        // create contact list to store search result 
         list<contact> lstContact = new list<contact>();
      
        // query contact records
         for(contact oCon : [Select id,Name,Email,FirstName,LastName,Phone
                             From Contact
                             WHERE name LIKE : sTempSearchKey]){
            lstContact.add(oCon);
         }
         
        //If there are no records found with searchKey then, throw aura exception with a message
          if(lstContact.size() == 0){
             throw new AuraHandledException('No Record Found..'); 
          }
          
         return lstContact;
     }
 }
 
HTML Template:

<template>
   <div class="slds-m-around_medium">
     
	 <div class="slds-m-bottom_small">
         <lightning-input type="text"
            value={sVal}
            label="Contact Name"
            onchange={updateSeachKey}
            ></lightning-input>
      </div>
	  
      <lightning-button label="Search"
         onclick={handleSearch}
         variant="brand"></lightning-button>
		 
      <!-- custom data table(with SLDS style) to display contact list  -->  
      <table class="slds-table slds-table_cell-buffer slds-table_bordered slds-m-top_small">
         <thead>
            <tr class="slds-line-height_reset">
               <th class="" scope="col">
                  <div class="slds-truncate" title="First Name">First Name</div>
               </th>
               <th class="" scope="col">
                  <div class="slds-truncate" title="Last Name">Last Name</div>
               </th>
               <th class="" scope="col">
                  <div class="slds-truncate" title="Phone">Phone</div>
               </th>
               <th class="" scope="col">
                  <div class="slds-truncate" title="Email">Email</div>
               </th>
            </tr>
         </thead>
		 
         <tbody>
            <!--iterate all contact records using for-each iteration -->    
            <template for:each={contacts} for:item="contact">
               <tr class="slds-hint-parent" key={contact.Id}>
                  <td>
                     <div class="slds-truncate">{contact.FirstName}</div>
                  </td>
                  <td>
                     <div class="slds-truncate">{contact.LastName}</div>
                  </td>
                  <td>
                     <div class="slds-truncate">
                        <lightning-formatted-phone value={contact.Phone} ></lightning-formatted-phone>
                     </div>
                  </td>
                  <td>
                     <div class="slds-truncate">
                        <lightning-formatted-email value={contact.Email} ></lightning-formatted-email>
                     </div>
                  </td>
               </tr>
            </template>
         </tbody>
      </table>
   </div>
</template>
 
Controller Class:


import { LightningElement,track} from 'lwc';
// import server side apex class method 
import getContactList from '@salesforce/apex/customSearchController.getContactList';
// import standard toast event 
import {ShowToastEvent} from 'lightning/platformShowToastEvent'
import allContacts from '@salesforce/apex/customSearchController.allContacts';
 
export default class customSearch extends LightningElement {
    @track tempContacts;
    //@track: Marks a property for internal monitoring. A template or function using- 
    //this property forces a component to rerender when the property’s value changes.
    @track contacts;
    sVal = '';
 
    connectedCallback() {
        allContacts()
        .then(result => {
            this.tempContacts=result;
            // set @track contacts variable with return contact list from server  
            this.contacts = result;
            console.log(result);
        })
      }
    // update sVal var when input field value change
    updateSeachKey(event) {
        this.sVal = event.target.value;
    }
 
    // call apex method on button click 
    handleSearch() {
        
        // if search input value is not blank then call apex method, else display error msg 
        if(this.sVal=='')
        {
            console.log(this.tempContacts);
            this.contacts=this.tempContacts;

        }
        if (this.sVal !== '') {
            getContactList({
                    searchKey: this.sVal
                })
                .then(result => {
                    this.searchKey='';
                    // set @track contacts variable with return contact list from server  
                    this.contacts = result;
                })
                .catch(error => {
                    
                    // display server exception in toast msg 
                    const event = new ShowToastEvent({
                        title: 'Error',
                        variant: 'error',
                        message: error.body.message,
                    });
                    this.dispatchEvent(event);
                    // reset contacts var with null   
                    this.contacts = null;
                });
        } 
        
    }
}

I hope this helps and in case if this comes handy can you please choose this as best answer so that it can be useful for others in the future.

Regards,
Anutej
ANUTEJANUTEJ (Salesforce Developers) 
I changed the updateSearchKey and I was able to achieve the expected result even if the search is not pressed:

updateSeachKey(event) {
        this.sVal = event.target.value;
        if(this.sVal=='')
        {
            console.log(this.tempContacts);
            this.contacts=this.tempContacts;
        }
    }

And I commented the above lines of code in handleSearch()