How to build autocomplete fields in visualforce pages

It is a very handy option to have autocomplete in picklists/dropdowns with large number of options. In this blog we will cover how to use a multiselect autocomplete field in a visualforce page. image

In this example we will display a list of email addresses configured in a custom setting as autocomplete options in an input field. It will also demonstrate how to pass the value that user is selecting to the controller.

It works based on jQuery UI autocomplete feature. Necessary css and JavaScript is available in CDN. you can find links to these CDN files in the visualforce page code.

Steps to Use

1) Create a custom setting and create records

   In this example, the list of email addresses that are displayed in autocomplete is pulled from name field in a custom setting. Please create a list custom setting with name AutocompleteEmails(AutocompleteEmails__c). Then create some email addresses as entry in the custom setting.

2) Create a page and controller

   Code used for achieving it can be found below,

 

   In the constructor of the class, email addresses are queried from the custom setting. Then these values are converted to JSON. This JSON file is assigned to a property in the controller, which is accessible in the page. Then in page level, using this JSON, autocomplete feature is created. Since <apex:inputText does not support applying autocomplete feature on it, autocomplete is created in a regular input field. The values that user select in this regular input is passed to controller using an <apex:inputHidden field. In the save method, this value is passed to controller and it is printed using a System.debug() statement.

Usage

This feature will be very useful when users are using a dropdown with large number of options in a visualforce page. This will help users to find the value they are searching for very easily.

2 comments:

  1. can you please help me i want to show account name with sap customer code in serach box.

    ReplyDelete