Search Contacts and Add to Account in Lightning Web Component

Posted on November 6, 2021 Post Thumbnail

Yo Trailblazers,

Welcome back to heySalesforce (-_-)

Today, We are going to create a Lightning Web Component, with the help of this component we can search contacts and add to Account from Account Record Page.

Let's have a look at demo itself.


What you'll Learn from Blog Post :)

1. Implement search functionality using SOSL.

2. Using of targetconfigs for component visibility.

Let's Start :)

Please have a look a following code and create a lwc component.

Apex Code:SearchController

public with sharing class SearchController {
    public static List<sObject> search(String objectName, List<String> fields, String searchTerm){
        String searchKeyword = searchTerm + '*';
        String returningQuery = '';
        returningQuery = objectName+' ( Id, '+String.join(fields,',')+')';
        String query = 'FIND :searchKeyword IN ALL FIELDS RETURNING '+returningQuery+' LIMIT 20';
        System.debug(' query '+query);
        List<List<sObject>> searchRecords = Search.Query(Query);
        return searchRecords.get(0);
    public static void updateContact( Id cId, Id accId){
            Contact c = new Contact();
            c.Id = cId;
            c.AccountId = accId;
            update c;


LWC: Html

    <lightning-card icon-name="utility:connected_apps" title="Search and Update Contacts">
        <lightning-spinner if:true={isLoading} alternative-text="Loading" size="small"></lightning-spinner>
        <div class="slds-form-element">
            <div class="slds-p-horizontal_medium">
                <lightning-input type="text" onchange={handleInputChange} placeholder={placeholder}>
            <ul class="slds-listbox slds-listbox_vertical">
                <template if:true={searchRecords} for:each={searchRecords} for:item="record" for:index="index">
                    <li class="slds-listbox__item" data-record-id={record.Id} key={record.Id}>
                        <div data-id={record.Id}
                            class="slds-media slds-listbox__option slds-listbox__option_entity slds-listbox__option_has-meta"
                            <span class="slds-media__figure slds-listbox__option-icon">
                                <span class="slds-icon_container slds-icon-standard-account">
                                    <svg class="slds-icon slds-icon_small" aria-hidden="true">
                                        <use xlink:href={ICON_URL}></use>0
                            <span class="slds-media__body">
                                <span class="slds-listbox__option-text slds-listbox__option-text_entity">
                                <span class="slds-listbox__option-meta slds-listbox__option-meta_entity">
                                    {record.FIELD2} &nbsp; {record.FIELD3}
                            <span if:false={record.FIELD4}>
                                <lightning-button label="Add to Account" title="Download action" value={record.Id}
                                    icon-name="utility:add" class="slds-m-left_x-small" onclick={addtoaccount}>
                            <span if:true={record.FIELD4}>
                                <lightning-button label="Add to Account" title="Download action" value={record.Id}
                                    icon-name="utility:add" disabled="true" class="slds-m-left_x-small"


import { LightningElement, track, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import search from '@salesforce/apex/';
import updateContact from '@salesforce/apex/SearchController.updateContact';
const DELAY = 300;
export default class anyname extends LightningElement {
    @api recordId;
    placeholder = 'Search';
    fields = ['Name', 'Email', 'Phone', 'AccountId'];
    @track error;
    @track searchRecords;
    objectLabel = 'Contact';
    isLoading = false;
    ICON_URL = '/apexpages/slds/latest/assets/icons/standard-sprite/svg/symbols.svg#contact';

    handleInputChange(event) {
        const searchKey =;
        this.isLoading = true;
        this.delayTimeout = setTimeout(() => {
            if (searchKey.length >= 2) {
                    objectName: this.objectLabel,
                    fields: this.fields,
                    searchTerm: searchKey
                    .then(result => {
                        let stringResult = JSON.stringify(result);
                        let allResult = JSON.parse(stringResult);
                        allResult.forEach(record => {
                            record.FIELD1 = record['Name'];
                            record.FIELD2 = record['Email'];
                            record.FIELD3 = record['Phone'];
                            record.FIELD4 = this.accountIdCheck(record['AccountId']);
                        this.searchRecords = allResult;

                    .catch(error => {
                        console.error('Error:', error);
                    .finally(() => {
                        this.isLoading = false;
        }, DELAY);
    addtoaccount(event) {
        let selectedConId =;
            cId: selectedConId,
            accId: this.recordId
            .then(result => {
                this.error = undefined;
                const evt = new ShowToastEvent({
                    title: 'Updated!',
                    message: 'Contact Updated Successfully!',
                    variant: 'success',
                for (var i = 0; i < this.searchRecords.length; i++) {
                    if (this.searchRecords[i].Id === selectedConId) {
                        this.searchRecords[i].FIELD4 = true;
            .catch(error => {
                console.error('Error:', error);
    accountIdCheck(accId) {
        if (accId === this.recordId)
            return true;
        return false


<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="">
        <targetConfig targets="lightning__RecordPage">

Note: Above component only available for account record page.

After creating all above files.

Add this component on account record page.


If you have any question Ask Me

Thanks for Reading :)

Write a comment for suggestions and hit the heart icon.


Tags: #lwc


There are no comments yet.
Your message is required.

Get notified of new posts