In the world of modern web development, enhancing user experience is a top priority. One of the most popular features for improving searchability is the “Typeahead” functionality, which provides dynamic suggestions as users type. This feature can significantly speed up data entry, reduce errors, and make your application feel more responsive.
In this blog, we’ll walk you through how to implement a Typeahead in a Salesforce Lightning Web Component (LWC). Whether you’re building a search box for records or a dynamic filtering system, this guide will give you the tools and understanding to implement this feature seamlessly in your Salesforce environment.
What is a Typeahead?
A Typeahead (also known as autocomplete) is a UI feature that automatically suggests possible matches based on the characters typed by the user. It helps users quickly find data by filtering through large datasets without having to type the full query. The suggestions are generally retrieved in real time based on the user’s input.
For example, as the user starts typing the name of a contact, the typeahead feature would suggest matching names from the Salesforce database.
Salesforce LWC Typeahead: Key Considerations
- Data Source: The data for typeahead suggestions typically comes from Salesforce records or external APIs. It’s important to efficiently fetch the right data.
- Search Threshold: Rather than fetching all records at once, limiting the number of results based on the search term is better to reduce load and enhance performance.
- User Experience (UX): Ensure that the suggestions appear as the user types and can be easily selected from the list.
Step 1: Setup the Lightning Web Component (LWC)
To begin, let’s create the basic structure of the Lightning Web Component. We’ll need an HTML file, a JavaScript file, and a CSS file.
1.1 Create the HTML File
<template> <lightning-input label="Search Contacts" value={searchTerm} onchange={handleSearchChange} placeholder="Search for a contact..." aria-live="assertive" class="search-box"> </lightning-input> <template if:true={suggestions.length}> <ul class="sugg-list"> <template for:each={suggestions} for:item="suggestion"> <li key={suggestion.Id} class="sugg-item" onclick={handleSuggestionSelect}> {suggestion.Name} </li> </template> </ul> </template> </template>
Explanation
<lightning-input>
: This is the input box where users will type their query. We bind it to a propertysearchTerm
and set up an event listenerhandleSearchChange
.- Suggestions: If there are matching results, a list (
<ul>
) is displayed, showing the names of the suggested contacts.
1.2 Create the JavaScript File
public void buildPathMap() { for (AssetNode node : refObj.values()) { if (!pathMap.containsKey(node.id)) { String path = getPath(node); pathMap.put(node.id, path); } } } // Recursive method to get the full path of a node private String getPath(AssetNode node) { if (String.isBlank(node.parentId)) { return node.name; // Base case: root node } AssetNode parentNode = refObj.get(node.parentId); if (parentNode != null) { String parentPath = getPath(parentNode); return parentPath + ' > ' + node.name; } return node.name; // In case parent doesn't exist } // Getter for the path map public Map<String, String> getPathMap() { return pathMap; }import { LightningElement, track } from 'lwc'; import searchContacts from '@salesforce/apex/ContactController.searchContacts'; export default class TypeaheadSearch extends LightningElement { @track searchTerm = ''; @track suggestions = []; // Handle input changes handleSearchChange(event) { this.searchTerm = event.target.value; if (this.searchTerm.length > 2) { this.fetchSuggestions(); } else { this.suggestions = []; } } // Fetch contact suggestions fetchSuggestions() { searchContacts({ searchTerm: this.searchTerm }) .then((result) => { this.suggestions = result; }) .catch((error) => { console.error("Error fetching suggestions", error); this.suggestions = []; }); } // Handle suggestion click handleSuggestionSelect(event) { this.searchTerm = event.target.innerText; this.suggestions = []; } }
Explanation
handleSearchChange()
: This method is triggered whenever the user types in the input box. If the user types more than 2 characters, it callsfetchSuggestions()
to retrieve the matching results.fetchSuggestions()
: This calls an Apex method (searchContacts
) that queries the Salesforce records and returns matching contacts based on thesearchTerm
.handleSuggestionSelect()
: When a user clicks on a suggestion, the search term is updated with the selected suggestion, and the list of suggestions is cleared.
1.3 Create the Apex Controller
Now, let’s create the Apex class that fetches the suggestions. This Apex class will use a SOQL query to find contacts based on the search term.
public class ContactController { @AuraEnabled(cacheable=true) public static List<Contact> searchContacts(String searchTerm) { String searchQuery = '%' + searchTerm + '%'; return [SELECT Id, Name FROM Contact WHERE Name LIKE :searchQuery LIMIT 5]; } }
Explanation
@AuraEnabled(cacheable=true)
: This makes the method available to Lightning Components and enables caching to improve performance.- SOQL Query: The query searches for contacts where the
Name
field contains thesearchTerm
, and we limit the results to 5 to avoid fetching too many records.
Step 2: Style the Component
You can style your component to make it visually appealing and user-friendly.
2.1 Add CSS for Typeahead Suggestions
.search-box { width: 100%; } .sugg-list { list-style-type: none; margin: 0; padding: 0; background-color: #fff; border: 1px solid #d8dde6; position: absolute; width: 100%; z-index: 10; } .sugg-item { padding: 10px; cursor: pointer; background-color: #f4f6f9; } .sugg-item:hover { background-color: #e1e5ea; }
Explanation
- Styling: The suggestions list is styled with a simple background, padding, and hover effect to make it more interactive.
Step 3: Test Your Typeahead in Salesforce
After deploying your component, add it to a Lightning Page or a record page in Salesforce. As users start typing, they should see suggestions appear dynamically.
Enhancing User Experience
Here are some ways to enhance the user experience:
- Debouncing: To avoid querying Salesforce on every keystroke, you can implement a debouncing technique to wait until the user stops typing for a certain period (e.g., 300ms).
- Loading Indicator: Add a loading spinner to show users that suggestions are being fetched.
- Error Handling: Implement user-friendly error messages if the Apex method fails or if no results are found.
Conclusion
In this blog, we’ve created a simple but effective Typeahead search functionality in Salesforce LWC. By leveraging Apex to retrieve dynamic suggestions, the component provides an interactive search experience for users, helping them find records faster and more efficiently.
This implementation adapts to various use cases, such as searching through records like Contacts, Accounts, Opportunities, or custom objects. You can customize this solution to fit your Salesforce application perfectly by understanding the key concepts and building blocks.
Happy coding, and feel free to share your feedback or improvements in the comments!