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.

demo

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 {
    @AuraEnabled
    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);
    }
    @AuraEnabled
    public static void updateContact( Id cId, Id accId){
            System.debug(cId);
            System.debug(accId);
            Contact c = new Contact();
            c.Id = cId;
            c.AccountId = accId;
            update c;
    }

}

LWC: Html

<template>
    <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}>
                </lightning-input>
            </div>
            <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"
                            role="option">
                            <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
                                    </svg>
                                </span>
                            </span>
                            <span class="slds-media__body">
                                <span class="slds-listbox__option-text slds-listbox__option-text_entity">
                                    {record.FIELD1}
                                </span>
                                <span class="slds-listbox__option-meta slds-listbox__option-meta_entity">
                                    {record.FIELD2} &nbsp; {record.FIELD3}
                                </span>
                            </span>
                            <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}>
                                </lightning-button>
                            </span>
                            <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"
                                    onclick={addtoaccount}>
                                </lightning-button>
                            </span>
                        </div>
                    </li>
                </template>
            </ul>
        </div>
    </lightning-card>
</template>

LWC: JS

import { LightningElement, track, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import search from '@salesforce/apex/SearchController.search';
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;
    searchTerm;
    delayTimeout;
    @track searchRecords;
    objectLabel = 'Contact';
    isLoading = false;
    ICON_URL = '/apexpages/slds/latest/assets/icons/standard-sprite/svg/symbols.svg#contact';

    handleInputChange(event) {
        //console.log(this.fields);
        window.clearTimeout(this.delayTimeout);
        const searchKey = event.target.value;
        this.isLoading = true;
        this.delayTimeout = setTimeout(() => {
            if (searchKey.length >= 2) {
                search({
                    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 = event.target.value;
        updateContact({
            cId: selectedConId,
            accId: this.recordId
        })
            .then(result => {
                this.error = undefined;
                const evt = new ShowToastEvent({
                    title: 'Updated!',
                    message: 'Contact Updated Successfully!',
                    variant: 'success',
                });
                this.dispatchEvent(evt);
                //console.log(this.searchRecords);
                for (var i = 0; i < this.searchRecords.length; i++) {
                    if (this.searchRecords[i].Id === selectedConId) {
                        //console.log(this.searchRecords[i].FIELD4);
                        this.searchRecords[i].FIELD4 = true;
                        //console.log(this.searchRecords[i].FIELD4);
                    }
                }
                eval("$A.get('e.force:refreshView').fire();");
            })
            .catch(error => {
                console.error('Error:', error);
            })
    }
    accountIdCheck(accId) {
        if (accId === this.recordId)
            return true;
        return false
    }
}

LWC:meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>Taskone</masterLabel>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordPage">
            <objects>
                <object>Account</object>
            </objects>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

Note: Above component only available for account record page.

After creating all above files.

Add this component on account record page.

result

If you have any question Ask Me

Thanks for Reading :)

Write a comment for suggestions and hit the heart icon.


497
0

Tags: #lwc

Comments

There are no comments yet.
Your message is required.

Get notified of new posts