Lightning Web Component Examples Search and Table
Apex Class :
Public Class getAccountRecords {
@AuraEnabled(cacheable=true)
public static List<Account> searchAccounts(String searchKey) {
String searchTerm = '%' + searchKey + '%';
return [ SELECT Id, Name,Industry,Phone FROM Account WHERE Name LIKE :searchTerm LIMIT 10];
}
}
searchAccounts.html
<template> <lightning-card title="Wired Account Search"> <div class="slds-p-around_medium"> <lightning-input type="text" label="Search Accounts by Name" placeholder="Enter name" onchange={handleSearchKeyChange}> </lightning-input> <template if:true={accounts}> <lightning-datatable key-field="Id" data={accounts} columns={columns} hide-checkbox-column> </lightning-datatable> </template> <template if:true={error}> <p class="slds-text-color_error">Error: {error.body.message}</p> </template> </div> </lightning-card> </template>
searchAccounts.js
import { LightningElement, track,wire } from 'lwc'; import searchAccounts from '@salesforce/apex/getAccountRecords.searchAccounts'; export default class AccountSearch extends LightningElement { @track searchKey = ''; @track accounts; @track error; get columns() { return [ { label: 'Name', fieldName: 'Name' }, { label: 'Industry', fieldName: 'Industry' }, { label: 'Phone', fieldName: 'Phone' } ]; } handleSearchKeyChange(event) { this.searchKey = event.target.value; } // Whenever searchKey changes, wire calls Apex @wire(searchAccounts, { searchKey: '$searchKey' }) wiredAccountList({ error, data }) { if (data) { this.accounts = data; this.error = undefined; } else if (error) { this.error = error; this.accounts = undefined; } } }
Comments
Post a Comment