With Lightning Web Components, we no longer have to click a button to perform filtering on tables. We can instead use a combination of event handlers and wire methods.
Here’s an example of a datatable that filters accounts according to the Industry picklist. Changing the value in the filter automatically refreshes the table to display the most relevant data.
HTML page:
<template>
<lightning-card title="Account PicklistValues">
<template if:true={IndustryPicklistValues.data}>
<lightning-combobox name="progress"
label="Industry"
value={value}
placeholder="-Select-"
options={IndustryPicklistValues.data.values}
onchange={handleChange} >
</lightning-combobox>
</template>
<div style="height: 300px;">
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
hide-checkbox-column>
</lightning-datatable>
</div>
</lightning-card>
</template>
Javascript Controller:
import { LightningElement, track, wire} from 'lwc';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';
import getAccountsByIndustry from '@salesforce/apex/PicklistFilterController.getAccountsByIndustry';
const columns = [
{ label: 'Name', fieldName: 'Name' },
{ label: 'Type', fieldName: 'Type' }
];
export default class PicklistFilter extends LightningElement {
@track value = '';
@track data = [];
@track columns = columns;
@wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })
objectInfo;
@wire(getPicklistValues, { recordTypeId: '$objectInfo.data.defaultRecordTypeId', fieldApiName: INDUSTRY_FIELD})
IndustryPicklistValues;
handleChange(event) {
this.value = event.detail.value;
}
@wire(getAccountsByIndustry, { industry : '$value' })
accountsByIndustryCallback({error,data}){
this.data = data;
}
}
Apex Controller:
public with sharing class PicklistFilterController {
@AuraEnabled(cacheable=true)
public static List<Account> getAccountsByIndustry(String industry){
return [SELECT Id, Name, Type FROM Account WHERE Industry=:industry];
}
}