Close

PrimeFaces - AutoComplete Example

[Last Updated: Jun 21, 2017]

Following example shows how to use AutoComplete component to display suggestions while entering text in a field.

JSF page

src/main/webapp/index.xhtml

<h:form>
    Enter Name:
    <p:autoComplete value="#{exampleBean.inputName}"
                    maxResults="10"
                    completeMethod="#{exampleBean.nameSuggestions}"/>

    <p:commandButton value="Submit" icon="ui-icon-check" update=":outputPanel"/>
</h:form>

The manage bean

@ManagedBean
@ViewScoped
public class ExampleBean {
  private String inputName;

  public List<String> nameSuggestions(String enteredValue) {
      List<String> matches = new ArrayList<>();
      //using data factory for getting suggestions
      for (String s : new DefaultNameDataValues().getFirstNames()) {
          if (s.toLowerCase().startsWith(enteredValue.toLowerCase())) {
              matches.add(s);
          }
      }
      return matches;
  }

  public String getInputName() {
      return inputName;
  }

  public void setInputName(String inputName) {
      System.out.println(inputName);
      this.inputName = inputName;
  }
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output


Example Project

Dependencies and Technologies Used:

  • primefaces 6.1 primefaces
  • jsf-api 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • jsf-impl 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • datafactory 0.8: Library to generate data for testing.
  • JDK 1.8
  • Maven 3.3.9

Auto Complete Example Select All Download
  • auto-complete-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • index.xhtml

    See Also