Dynamic Search in Lightning WebComponent




Video link
========
https://www.youtube.com/watch?v=i2_Zgw5OI_A&t=14s


Apex class
==========
public with sharing class ContactSearchController
{
    @AuraEnabled(cacheable=true)
    public static List<Contact> getAllContacts(String searchKey)
    {
        List<Contact> returnconlist=new List<Contact>();
        String searchWord='%'+searchKey+'%';
        for(Contact con:[select LastName from Contact where LastName like:searchWord])
        {
            returnconlist.add(con);
}
        if(returnconlist.isEmpty())
        {
            System.debug('No Records found'+returnconlist.size());
        }
        return returnconlist;
   
    }

 
 
conSearch.html
==============
<template>

    <lightning-card title="ContactSearchFunctionality" icon-name="custom:custom63">
        <lightning-input label="Enter LastName"  style="width:50%;" placeholder="Search Contacts" onchange={handleClick} value={conLastName}>
        </lightning-input>
        <div class="slds-m-around_medium">
            <template if:true={records}>
                <template for:each={records} for:item="contact">
                    <p key={contact.Id}>
                        {contact.LastName}</p>
                </template>
            </template>
            <template if:true={errors}>
             Error in fetching the data
            </template>
            <template if:false={records}>
                No Contacts found
                </template>
        </div>
    </lightning-card>
</template>

conSearch.js
============
import { LightningElement ,api, wire} from 'lwc';
import getAllContacts from '@salesforce/apex/ContactSearchController.getAllContacts';
export default class ConSearch extends LightningElement {
    @api  conLastName;
    @api records;
    @api errors;
    @wire(getAllContacts, {searchKey: '$conLastName' })
    wiredContact({ error, data }) {
        if (data) {
            this.records = data;
            this.errors = undefined;
        } else{
            this.errors = error;
            this.records = undefined;
        }
    }
    handleClick(event){
        const conName=event.target.value;
        this.conLastName=conName;
        console.log('***Entered value****'+this.conLastName);
    }


}




Comments