~
How to build autocomplete fields in visualforce pages

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.
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
- 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.
- Create a page and controller
Code used for achieving it can be found below,
<apex:page controller="AutoCompleteController" ID="page" standardStylesheets="false" sidebar="false">
<apex:stylesheet value="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"/>
<apex:stylesheet value="//code.jquery.com/ui/1.11.3/themes/sunny/jquery-ui.css"/>
<apex:includeScript value="//code.jquery.com/jquery-1.10.2.js"/>
<apex:includeScript value="//code.jquery.com/ui/1.11.3/jquery-ui.js"/>
<apex:form id="form">
<div class="container">
<!-- we cannot bind jquery UI autocomplete directly to apex input fields. So it needs to be bind to some regular input field then on form submission, the values need to be copied to some hidden apex input field-->
<input type="text" id="autocomplete" class="input-lg"/>
<apex:inputhidden value="{!selectedEmails}" id="selectedEmails"/>
<apex:commandButton value="Save" action="{!receiveValues}" onclick="setHiddenInput();" styleClass="btn btn-success"/>
</div>
</apex:form>
<script>
//Method needed for adding autocomplete feature in TO field.
var autocompleteEmails ={!toEmailJSON};
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$(function() {
$( "#autocomplete" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).autocomplete( "instance" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
autocompleteEmails, extractLast( request.term ) ) );
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
//Method to set value from normal HTML input to hidden apex input field.
function setHiddenInput(){
var selectedEmails = $("#autocomplete").val();
document.getElementById("page:form:selectedEmails").value = selectedEmails;
}
</script>
</apex:page>
public class AutoCompleteController {
//String property to pass JSON data to page
public String toEmailJSON{get;set;}
//String property to save the values selected by user
public String selectedEmails{get;set;}
//Constructor of the class where email addresses are obtained from custom setting and converted to JSON
public autocompleteController(){
Set<String> autocompleteEmailSet = AutocompleteEmails__c.getAll().keyset();
toEmailJSON = JSON.serialize(autocompleteEmailSet);
}
//Method to demonstrate that values are coming to controller on button click
public PageReference receiveValues() {
//Debugging the value passed from page
System.debug(selectedEmails);
return null;
}
}
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.