Implementing custom record search functionality using Lightning web component.
Business Case:
Adam is Senior Application Developer in TwoPir Consulting Pvt Ltd. He wants a custom object record search functionality in salesforce so he can quickly search any record quickly.
Solution:
we can create custom record search functionality in salesforce lightning web components.
He is developing a custom search for standard contact subject records with a lightning input field.
Adam Created below lightning web component:
customSearchLWC.html:
value={sVal}
label=”Contact Name”
onchange={updateSeachKey}
>
onclick={handleSearch}
variant=”brand”>
class=”slds-table slds-table_cell-buffer slds-table_bordered slds-m-top_small”>
First Name
Last Name
Phone
Email
{contact.FirstName}
{contact.LastName}
CustomSearchLWC.js:
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’
export default class CustomSearchLWC extends LightningElement {
@track contacts;
sVal = ”;
// 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 !== ”) {
getContactList({
searchKey: this.sVal
})
.then(result => {
// 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;
});
} else {
// fire toast event if input field is blank
const event = new ShowToastEvent({
variant: ‘error’,
message: ‘Search text missing..’,
});
this.dispatchEvent(event);
}
}
}
CustomSearchLWC.XML:
xmlns=”http://soap.sforce.com/2006/04/metadata” fqn=”CustomSearchLWC”>
46.0
true
lightning__AppPage
lightning__RecordPage
lightning__HomePage