LWC: Build Account Filter Component With Search
In this comprehensive guide, we'll walk through the process of creating a Lightning Web Component (LWC) that displays Account records in a data table, complete with filtering and search capabilities. This LWC component will not only enhance your Salesforce user experience but also provide a practical example of leveraging LWC's power and flexibility. We will cover everything from setting up the LWC component to building the Apex server-side controller, ensuring a smooth and efficient development process. By the end of this article, you'll have a fully functional component that you can adapt and use in your own Salesforce org. Let’s dive in and get started!
1. Introduction to LWC and Account Filtering
Lightning Web Components (LWCs) are a modern framework for building user interfaces on the Salesforce platform. They leverage web standards, making them lightweight, fast, and easy to learn for developers familiar with HTML, JavaScript, and CSS. LWCs promote reusability and maintainability, which are crucial for building scalable Salesforce applications. This guide focuses on creating an LWC component to display and filter Account records, a common requirement in many Salesforce implementations. Understanding the basics of LWC and its architecture is essential before diving into the implementation details. This initial overview sets the stage for a deeper exploration of the components and code required to achieve our goal.
Understanding the Importance of Account Filtering
Account filtering is a critical feature in any CRM system like Salesforce. It allows users to quickly find and manage the Account records they need, improving efficiency and productivity. Without proper filtering capabilities, users might spend significant time searching through numerous records, leading to frustration and decreased efficiency. Our LWC component will address this issue by providing a user-friendly interface with a search input field, enabling users to filter Accounts based on their names. Furthermore, displaying key information such as Account ID, Record Type, and Created Date in a data table will offer a comprehensive view of each Account, enhancing the user experience and making data management more streamlined.
2. Setting Up the LWC Component
Before we begin coding, we need to set up the LWC component in our Salesforce environment. This involves creating the necessary files and defining the component's metadata. The basic structure of an LWC component includes an HTML file for the template, a JavaScript file for the logic, and a metadata file to configure the component's properties. We'll start by creating these files and then move on to defining the component's structure and behavior. This setup is the foundation for the rest of our development process, ensuring that our component is correctly recognized and can interact with the Salesforce platform.
Creating the LWC Files
First, you'll need to use the Salesforce CLI or your preferred IDE to create a new LWC. Let's name our component accountFilter. Here’s how you can create the necessary files:
- Create a new directory named
accountFilterin your LWC modules directory. - Inside the
accountFilterdirectory, create three files:accountFilter.htmlaccountFilter.jsaccountFilter.js-meta.xml
These files will contain the HTML template, JavaScript logic, and metadata configuration for our component, respectively. Each file plays a specific role in defining the component's structure, behavior, and properties, allowing us to build a cohesive and functional user interface.
Defining the Component's Metadata
The metadata file (accountFilter.js-meta.xml) defines the component's configuration, such as its API version, targets (where the component can be used), and design-time attributes. Here’s a basic example of the metadata file content:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>58.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__AppPage">
<property name="maxRecords" type="Integer" default="10" label="Max Records to Display" description="Maximum number of records to display initially"/>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>
In this metadata file, we set isExposed to true to make the component available in Lightning App Builder and other contexts. The <targets> section specifies where the component can be used, such as on App Pages, Record Pages, and Home Pages. The <targetConfigs> section allows us to define properties that can be configured in the Lightning App Builder, such as the maximum number of records to display initially (maxRecords). This metadata configuration ensures that our component is correctly integrated into the Salesforce environment and can be easily customized by administrators.
3. Building the HTML Template
The HTML template (accountFilter.html) defines the structure and layout of our LWC component. It includes the data table to display Account records and the search input field for filtering. We'll use the lightning-datatable component to display the Account data and the lightning-input component for the search input. Creating a well-structured and user-friendly HTML template is crucial for the overall usability of our component.
Designing the User Interface
Our component's UI will consist of two main parts:
- A search input field at the top for filtering Accounts by name.
- A data table to display the Account records, including columns for Account Name, Account ID, Record Type, and Created Date.
This layout ensures that users can easily search for specific Accounts and view their details in a clear and organized manner. The search input field provides a quick way to narrow down the results, while the data table displays the essential information for each Account. This combination of search and display elements makes our component highly functional and user-friendly.
HTML Structure
Here’s the basic HTML structure for our component:
<template>
<lightning-card title="Account Filter">
<div class="slds-p-around_medium">
<lightning-input type="search" label="Search Accounts" value={searchTerm} onchange={handleSearchTermChange}></lightning-input>
</div>
<template if:true={accounts}>
<lightning-datatable
key-field="Id"
data={accounts}
columns={columns}>
</lightning-datatable>
</template>
<template if:false={accounts}>
<div class="slds-align_absolute-center">
No Accounts found.
</div>
</template>
</lightning-card>
</template>
In this HTML template:
- We use
lightning-cardto provide a container for our component with a title. lightning-inputis used to create a search input field, which is bound to thesearchTermproperty in our JavaScript file. Theonchangeevent is handled by thehandleSearchTermChangemethod.lightning-datatableis used to display the Account records. Thekey-fieldattribute specifies the unique identifier for each record, anddatais bound to theaccountsproperty, which will hold the Account data. Thecolumnsproperty defines the columns to display in the table.- Conditional directives (
if:trueandif:false) are used to display the data table if Accounts are found or a message if no Accounts are found. This ensures that the user interface provides clear feedback in both scenarios.
4. Implementing the JavaScript Logic
The JavaScript file (accountFilter.js) contains the logic for our LWC component. This includes fetching Account records from the server, handling the search input, and updating the data table. We'll use the @wire decorator to fetch initial Account records and an imperative Apex call to filter Accounts based on the search term. Writing efficient and maintainable JavaScript code is crucial for the component's performance and functionality.
Fetching Account Records
We'll start by importing the necessary modules and defining the columns for our data table. Then, we'll use the @wire decorator to call an Apex method that fetches the initial Account records. This approach leverages the Reactive Programming model, ensuring that our component automatically updates when the data changes.
JavaScript Code Structure
Here’s the basic JavaScript structure for our component:
import { LightningElement, wire, track } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
const COLUMNS = [
{ label: 'Account Name', fieldName: 'Name', type: 'text' },
{ label: 'Account ID', fieldName: 'Id', type: 'text' },
{ label: 'Record Type', fieldName: 'RecordType.Name', type: 'text' },
{ label: 'Created Date', fieldName: 'CreatedDate', type: 'date' }
];
export default class AccountFilter extends LightningElement {
@track accounts;
@track columns = COLUMNS;
@track searchTerm = '';
@track maxRecords;
@wire(getAccounts, { maxRecords: '$maxRecords', searchTerm: '$searchTerm' })
wiredAccounts({ error, data }) {
if (data) {
this.accounts = data;
} else if (error) {
console.error('Error fetching accounts:', error);
}
}
handleSearchTermChange(event) {
this.searchTerm = event.target.value;
}
connectedCallback() {
this.maxRecords = this.getMaxRecordsFromConfig();
}
getMaxRecordsFromConfig() {
// Get the maxRecords value from the component configuration
const config = this.template.querySelector('lightning-card');
if (config) {
return config.maxRecords;
}
return 10; // Default value
}
}
In this JavaScript code:
- We import
LightningElement,wire, andtrackfrom thelwcmodule.wireis used for the Reactive Programming model, andtrackis used to track private reactive properties. - We import the
getAccountsApex method from theAccountControllerclass. COLUMNSis an array that defines the columns for our data table, including the label, field name, and data type for each column.accounts,columns,searchTerm, andmaxRecordsare tracked properties that store the Account data, column definitions, search term, and maximum number of records to display, respectively.- The
@wiredecorator is used to call thegetAccountsApex method with themaxRecordsandsearchTermparameters. The results are handled by thewiredAccountsmethod, which updates theaccountsproperty with the fetched data or logs an error if one occurs. - The
handleSearchTermChangemethod is called when the user enters a search term in the input field. It updates thesearchTermproperty with the new value. - The
connectedCallbacklifecycle hook is used to set the initial value formaxRecordsby callinggetMaxRecordsFromConfig, which retrieves the value from the component configuration or defaults to 10.
5. Creating the Apex Server-Side Controller
The Apex server-side controller (AccountController.cls) is responsible for fetching Account records from the Salesforce database. This controller will include a method to retrieve the initial set of Accounts and another method to filter Accounts based on the search term. Writing efficient and secure Apex code is crucial for the performance and security of our component.
Apex Class Structure
Our Apex class will include the following:
- A method to fetch Accounts with a limit on the number of records returned.
- A method to filter Accounts based on a search term, using a dynamic SOQL query to ensure flexibility and security.
This structure allows us to retrieve the initial set of Accounts efficiently and filter them dynamically based on user input. The use of dynamic SOQL ensures that our queries are secure and can handle various search terms without exposing our application to SOQL injection vulnerabilities.
Apex Code
Here’s the Apex code for our AccountController class:
public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<Account> getAccounts(Integer maxRecords, String searchTerm) {
String query = 'SELECT Id, Name, RecordType.Name, CreatedDate FROM Account';
String whereClause = '';
if (String.isNotBlank(searchTerm)) {
whereClause = ' WHERE Name LIKE :(\'%' + searchTerm + '%\')';
}
String limitClause = ' LIMIT :maxRecords';
String finalQuery = query + whereClause + limitClause;
return Database.query(finalQuery);
}
}
In this Apex code:
- We define the
AccountControllerclass with thewith sharingkeyword to enforce sharing rules. - The
getAccountsmethod is annotated with@AuraEnabled(cacheable=true)to make it accessible to our LWC component and enable caching of the results. - The method takes
maxRecordsandsearchTermas parameters, allowing us to limit the number of records returned and filter them based on the search term. - We construct a dynamic SOQL query to fetch the Account records. The base query selects the Id, Name, RecordType.Name, and CreatedDate fields from the Account object.
- If a search term is provided, we add a
WHEREclause to filter the Accounts based on the Name field. We use theLIKEoperator and wildcard characters (%) to perform a partial match search. - We add a
LIMITclause to restrict the number of records returned to themaxRecordsvalue. - Finally, we use
Database.queryto execute the dynamic SOQL query and return the results.
6. Deploying and Testing the Component
Once we've built the LWC component and the Apex controller, the next step is to deploy them to our Salesforce org and test their functionality. This involves pushing the code to the org, adding the component to a Lightning page, and verifying that the filtering and search features work as expected. Thorough testing is essential to ensure that our component meets the requirements and provides a seamless user experience.
Deploying the Code
To deploy the code, you can use the Salesforce CLI or your preferred IDE. Here’s how you can deploy using the Salesforce CLI:
-
Open a terminal or command prompt.
-
Navigate to your project directory.
-
Run the following command:
sfdx force:source:deploy -p force-app/main/default/lwc/accountFilter,force-app/main/default/classes/AccountController.cls ```
This command deploys the accountFilter LWC component and the AccountController Apex class to your Salesforce org. Make sure to replace force-app/main/default with your project's source directory if it's different.
Adding the Component to a Lightning Page
After deploying the code, you can add the component to a Lightning page using the Lightning App Builder:
- Go to Setup in your Salesforce org.
- Search for Lightning App Builder and select it.
- Open an existing Lightning page or create a new one.
- Find the
accountFiltercomponent in the list of custom components. - Drag the component onto the page.
- Configure the component's properties, such as the maximum number of records to display, in the properties panel.
- Save and activate the page.
Testing the Component
To test the component:
- Open the Lightning page where you added the component.
- Verify that the data table displays the initial set of Account records.
- Enter a search term in the input field and verify that the table updates to display only the matching Accounts.
- Check for any errors in the browser console and address them as needed.
By following these steps, you can ensure that your LWC component functions correctly and provides the desired filtering and search capabilities.
Conclusion
In this guide, we've walked through the process of creating an LWC component to display and filter Account records in a data table. We covered setting up the LWC component, building the HTML template, implementing the JavaScript logic, and creating the Apex server-side controller. By following these steps, you can create a functional and user-friendly component that enhances the user experience in your Salesforce org.
Key Takeaways
- LWCs are a powerful tool for building modern user interfaces on the Salesforce platform.
- Account filtering is a critical feature for improving efficiency and productivity in Salesforce.
- The
@wiredecorator and imperative Apex calls can be used to fetch data from the server. - Dynamic SOQL queries provide flexibility and security when filtering data.
- Thorough testing is essential to ensure that your component functions correctly.
By mastering these concepts and techniques, you can build robust and scalable LWC components to meet your specific business needs. For further learning and exploration, consider checking out the official Salesforce Lightning Web Components documentation and Trailhead modules. Salesforce Lightning Web Components Documentation.