PrimeFaces : String Input Elements

In our previous primefaces tutorials, we saw installation setup and some dataInput components. In this tutorial, we will work on String Input components like autoComplete (for suggestions), inputMask (Constrained String Input), colorPicker (HTML color chooser), inplace (editable when clicked) and editor.

1. p:autoComplete Overview

  • It’s appearance is like a textfield with dropdown of suggested completions.
  •  And behavior is, developer can choose whether user is forced to accept one of the suggestions or can also enter arbitrary text.
  •  Purpose is to collect Strings from user and value is not converted. Bean property must be a String.

Summary of attributes:

 Syntax: <p:autoComplete .../>
  1. value : Should point to bean property of type String.
  2. completeMethod: A bean property referring to a server-side method that takes a String as input (the text entered so far) and returns a List (the suggestions to show).
  3. forceSelection (true or false [default]): Is user constrained to choose a selection (true), or is free text allowed (false).
  4. minQueryLength (integer[default 1]): Number of chars before suggestions start.
  5. queryDelay (integer[default 300]): Number of milliseconds before contacting server. Default 300.
  6. multiple (true or false [default]): Can user select more than one choice and send it as List?

2. p:autoComplete Implementation

In this example we check how to give options to user for selecting a computer programming language and restricting with the given list of options.

Managed Bean: LanguageBean

Unlike many client-side autocompleters, there is no builtin functionality as to how matches are done (front of text vs. middle of text, case sensitive, etc.). The method returns a List designating the suggestions, and the way the List is created is totally up to the developer. Here, I choose to do a case-insensitive match against the front of the user data.

package net.javabeat.primefacescomp;
import java.util.*;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;

import org.primefaces.event.*;

@ManagedBean
public class LanguageBean {
  // 100 most popular programming languages, according to
  // http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html
  // The first half are in order of popularity, the second half
  // are in alphabetical order.
  private static final String languageString =
    "Java,C,C++,PHP,C#,Python,Visual Basic,Objective-C,Perl,Ruby,JavaScript,Delphi," +
    "Lisp,SQL,Pascal,Ada,NXT-G,SAS,RPG,Lua,ABAP,Object Pascal,Go,Scheme,Fortran," +
    "Tc,D,COBOL,Logo,CL,APL,JavaFX Script,R,JScript.NET,C shell,ActionScript,Scratch," +
    "IDL,Haskell,Alice,Prolog,Erlang,Smalltalk,Forth,Awk,ML,Scala,ABC,Algol,Applescript," +
    "Bash,bc,Beta,CFML,cg,Clean,Clipper,Cobra,cT,Curl,Dylan,Eiffel,Euphoria,F#,Factor," +
    "Groovy,Icon,Io,J,LabVIEW,LabWindows/CVI,MAD,MAX/MSP,Modula-2,Modula-3,MUMPS,Natural," +
    "Oberon,Objective Caml,Occam,Oz,PL/I,Postscript,PowerShell,Q,REALbasic,S,SIGNAL,SPSS," +
    "Squirrel,Verilog,VHDL,XBase,XSLT,Z shell";
  private static final String[] languageArray = languageString.split(",");

  private String language;
  private List<String> languages;

  public String getLanguage() {
    return(language);
  }

  public void setLanguage(String language) {
    this.language = language;
  }

  public List<String> getLanguages() {
    return(languages);
  }

  public void setLanguages(List<String> languages) {
    this.languages = languages;
  }

  public List<String> completeLanguage(String languagePrefix) {
    List<String> matches = new ArrayList<String>();
    for(String possibleLanguage: languageArray) {
      if(possibleLanguage.toUpperCase().startsWith(languagePrefix.toUpperCase())) {
        matches.add(possibleLanguage);
      }
    }
    return(matches);
  }

  public String register() {
    return("show-language");
  }

  public String register2() {
    return("show-languages");
  }

}

Input Page: autocomplete-1.xhtml

Typed ‘J’ on textbox then immediately it will show the following selection list which are coming from LangaugeBean.

image001

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.org/ui">
<h:head><title>p:autoComplete</title>
</h:head>
<h:body>

<h1 class="ui-widget-header ui-corner-all" align="center">p:autoComplete</h1>
<br/>
<p:fieldset legend="Basic Autocompleter">
<h:form>
   <h2>Choose a Programming Language</h2>
   Only entries from the suggestions are allowed.
   <p:messages/>
   <p:autoComplete value="#{languageBean.language}"
                   completeMethod="#{languageBean.completeLanguage}"
                   forceSelection="true"
                   required="true"
                   requiredMessage="You must choose a language"/>
   <p:commandButton action="#{languageBean.register}"
                    value="Submit" ajax="false"/>
</h:form>
</p:fieldset>
</h:body></html>

Ajax input page: autocomplete-3.xhtml

Let’s see one more sample for multiple option selection with having Ajax calls for selecting and unselecting the text.

image002

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.org/ui">
<h:head><title>p:autoComplete</title>
</h:head>
<h:body>
<h1 class="ui-widget-header ui-corner-all" align="center">p:autoComplete</h1>
<br/>
<p:fieldset legend="Autocompleter with Multiple Selection (and Ajax?)">
<h:form>
   <h2>Choose a Programming Language</h2>
   Only entries from the suggestions are allowed.
   <p:messages id="messages"/>
   <p:autoComplete value="#{languageBean.languages}"
                   completeMethod="#{languageBean.completeLanguage}"
                   required="true"
                   requiredMessage="You must choose a language"
                   multiple="true">
     <p:ajax event="itemSelect"
             listener="#{languageBean.selectListener}"
             update="messages"/>
     <p:ajax event="itemUnselect"
             listener="#{languageBean.unselectListener}"
             update="messages"/>
   </p:autoComplete>
   <p:commandButton action="#{languageBean.register2}"
                    value="Submit" ajax="false"/>
</h:form>
</p:fieldset>
</h:body></html>

Managed Bean for ajax calls

Used the same managed bean which used for above example, however the difference is to add the listeners.

  public void selectListener(SelectEvent event) {
    String itemSelected = event.getObject().toString();
    String message =
      String.format("Added '%s' to selections", itemSelected);
    FacesContext context = FacesContext.getCurrentInstance();
    context.addMessage(null, new FacesMessage(message));
  }

  public void unselectListener(UnselectEvent event) {
    String itemSelected = event.getObject().toString();
    String message =
      String.format("Removed '%s' from selections", itemSelected);
    FacesContext context = FacesContext.getCurrentInstance();
    context.addMessage(null, new FacesMessage(message));
  }

3. p:input-mask: Overview

  • Appearance and behavior: is a textfield with template text that constrains the values that the user can enter.
  • Purpose: for collecting strings from user– Value is not converted. Bean property must be string. Spaces, dashes and other template text are sent with the string and must be parsed on server.
  • Documentation lacking– PrimeFaces documentation is not much about this component. But uses the JQuery MaskedInput plugin, so read from here. http://digitalbush.com/projects/masked-input-plugin/

Summary of attributes:

Syntax: < p:input-mask .../>
  •  mask: Each character has four possible values
    1. ‘9’ Permits only a number to be entered there.
    2. ‘a’ Permits only a letter (upper or lower case) to be entered there.
    3. ‘*’ Permits a letter or a number to be entered there.
    4. Anything else. Literal text that is displayed to the user and is not editable. This text does become part of value sent to server.
  •  Value:  Should point to bean property of type String. Literal text in textfield (e.g., parenthesis and dashes in phone number) is part of value sent to server, so server method must parse it

4. p:input-mask implementation

In this example we will see how to mask

  1. Phone number (no extension)
  2. Phone number with extension
  3. Social Security Number
  4. Product key
  5. License plate value
  6. Arbitrary message (with p:inputText) for comparison
  7. Arbitrary message (with h:inputText) for comparison
  8. Incomplete values will be treated as missing values, and requiredMessage will be shown.

Managed Bean: MaskBean

This Managed bean simply have’s all the getters and setters required for each listed component.

package net.javabeat.primefacescomp;

import javax.faces.bean.ManagedBean;

@ManagedBean
public class MaskBean {
  private String phone, phoneWithExt, ssn, productKey, license, message1, message2;

  public String getPhone() {
    return(phone);
  }

  public void setPhone(String phone) {
    this.phone = phone;
  }

  public String getPhoneWithExt() {
    return(phoneWithExt);
  }

  public void setPhoneWithExt(String phoneWithExt) {
    this.phoneWithExt = phoneWithExt;
  }

  public String getSsn() {
    return(ssn);
  }

  public void setSsn(String ssn) {
    this.ssn = ssn;
  }

  public String getProductKey() {
    return(productKey);
  }

  public void setProductKey(String productKey) {
    this.productKey = productKey;
  }

  public String getLicense() {
    return(license);
  }

  public void setLicense(String license) {
    this.license = license;
  }

  public String getMessage1() {
    return(message1);
  }

  public void setMessage1(String message1) {
    this.message1 = message1;
  }

  public String getMessage2() {
    return(message2);
  }

  public void setMessage2(String message2) {
    this.message2 = message2;
  }

  public String register() {
    return("show-input-mask-data");
  }
}

Input Page : input-mask.xhtml

This input page is having all the input fields with mask done each text fields as mentioned.

image003

image004


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:p="http://primefaces.org/ui">
<h:head><title>p:inputMask</title>
<link href="./css/extra-styles.css"
      rel="stylesheet" type="text/css"/>
</h:head>
<h:body>
<h1 class="ui-widget-header ui-corner-all" align="center">p:inputMask</h1>
<br/>
<p:fieldset legend="Enter Info">
<h:form>
<h:panelGrid columns="3" class="formTable">
  Phone:
  <p:inputMask mask="(999) 999-9999"
               value="#{maskBean.phone}"
               required="true" id="phone"
               requiredMessage="Missing or incomplete phone number"/>
  <p:message for="phone"/>

  Phone with Ext:
  <p:inputMask mask="(999) 999-9999 x999"
               value="#{maskBean.phoneWithExt}"
               required="true" id="phoneWithExt"
               requiredMessage="Missing or incomplete phone number with extension"/>
  <p:message for="phoneWithExt"/>

  SSN:
  <p:inputMask mask="999-99-9999"
               value="#{maskBean.ssn}"
               required="true" id="ssn"
               requiredMessage="Missing or incomplete social security number"/>
  <p:message for="ssn"/>

  Product Key:
  <p:inputMask mask="aaa-999-a999"
               value="#{maskBean.productKey}"
               required="true" id="productKey"
               requiredMessage="Missing or incomplete product key"/>
  <p:message for="productKey"/>

  License Plate:
  <p:inputMask mask="*****"
               value="#{maskBean.license}"
               required="true" id="license"
               requiredMessage="Missing or incomplete license plate"/>
  <p:message for="license"/>

  Free-text message:
  <p:inputText value="#{maskBean.message1}"
               required="true" id="message1"
               requiredMessage="Missing message"/>
  <p:message for="message1"/>

  Free-text message:
  <h:inputText value="#{maskBean.message2}"
               required="true" id="message2"
               requiredMessage="Missing message"/>
  <p:message for="message2"/>
</h:panelGrid>
  <p:commandButton action="#{maskBean.register}"
                   value="Register" ajax="false"/>
</h:form>
</p:fieldset>
</h:body></html>

5. p:colorPicker: Overview

  • Appearance and behavior is a small button that, when clicked, pops up interactive color chooser and Color chooser lacks a close button or “x” so we must click off of color picker to close it
  • Purpose: for collecting color specs , so value is String of form “rrggbb” in hex. Note that value does notstart with “#”.

Summary of Attributes

Syntax: < p: :colorPicker.../>
  1. value should point to bean property of type String. Value sent will be of form “rrggbb” (in hex), with no leading “#”.
  2. mode (popup [default] or inline): it determines whether the color picker pops up when user presses the button, or if the color picker is already open and embedded in the page.                                                                                               It Works just like the mode option to p:calendar.

6. p: colorPicker Implementation

In this example we see, how we set Foreground color with popup color picker and Background color With popup color picker.

Managed Bean ColorPreferences.java

This managedbean contains all input component’s properties .However the String sent does not contain “#”, so we have to explicitly add it to the output.(refer to style method)

package net.javabeat.primefacescomp;

import java.io.*;
import javax.faces.bean.*;

@ManagedBean
@SessionScoped
public class ColorPreferences implements Serializable {
  private String foreground="0000ff", background="fdf5e6";

  public String getForeground() {
    return(foreground);
  }

  public void setForeground(String foreground) {
    this.foreground = foreground;
  }

  public String getBackground() {
    return(background);
  }

  public void setBackground(String background) {
    this.background = background;
  }

  public String getStyle() {
    String style =
      String.format("color: #%s; background-color: #%s",
                    foreground, background);
    return(style);
  }

  public String showSample() {
    return("show-colors");
  }
}

Input page colorpicker.xhtml

image005

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:p="http://primefaces.org/ui">
<h:head><title>p:colorPicker</title>
<link href="./css/extra-styles.css"
      rel="stylesheet" type="text/css"/>
</h:head>
<h:body>
<h1 class="ui-widget-header ui-corner-all" align="center">p:colorPicker</h1>
<br/>
<p:fieldset legend="Choose Preferred Colors (Popup)">
<h:form>
<h:panelGrid columns="2" class="formTable">
  Foreground:
  <p:colorPicker value="#{colorPreferences.foreground}"/>

  Background:
  <p:colorPicker value="#{colorPreferences.background}"/>

</h:panelGrid>
  <p:commandButton action="#{colorPreferences.showSample}"
                   value="Show Sample of Colors Selected"
                   ajax="false"/>
</h:form>
</p:fieldset>
<br/>
<p:fieldset legend="Choose Preferred Colors (Inline)">
<h:form>
<h:panelGrid columns="2" class="formTable">
  Foreground:
  <p:colorPicker value="#{colorPreferences.foreground}"
                 mode="inline"/>

  Background:
  <p:colorPicker value="#{colorPreferences.background}"
                 mode="inline"/>

</h:panelGrid>
  <p:commandButton action="#{colorPreferences.showSample}"
                   value="Show Sample of Colors Selected"
                   ajax="false"/>
</h:form>
</p:fieldset>
</h:body></html>

7. p:inplace overview

  • Appearance and behavior is a text that, when clicked, turns into input elements.
  • Purpose: for collecting arbitrary input of any type of input elements.

Summary of Attributes

 Syntax: <p:inplace ...>input elements</p:inplace>
  1. No value attribute: Text is displayed, but no value is sent as part of a form. No corresponding bean property. When you click on the text, the text disappears and the elements inside are displayed instead.The text that is displayed is the “value” attribute of the first element inside the body, unless “label” is used.
  2. label : If you want text to be something different than “value” of first element. The label attribute may contain EL elements.
  3. editor (true or false [default]) – If true, shows save and cancel icons. Clicking both closes the content and reverts to the text. You can also attach Ajax listeners to respond to “save” and “cancel” events, but icons also used for toggling. Elements reevaluated when clicked.

8. p:inplace implementation

We will take result of above example in color picker .we show sample text which can be editable onclick.
Along with using same managedbean from the above example , also using below Manged bean for random pictures.

Managed Bean : ImageBean

This bean we are using to generate random number for picking up image from specified directory.

package net.javabeat.primefacescomp;

import java.util.Random;

import javax.faces.bean.*;

@ApplicationScoped
@ManagedBean
public class ImageBean {
  private int numImages = 22;
  private Random r = new Random();
  private String template =
    "/images/internet-cafes/cafe-%s.jpg";

  public String getRandomImage() {
    int num = r.nextInt(numImages) + 1;
    // The path will be used with "url" attribute of h:graphicImage.
    // So, path is relative to WebContent in Eclipse project (to project root when deployed).
    // If you want it relative to WebContent/resources, move "images" to resources and use
    // h:graphicImage name="cafe-x.jpg" library="images/internet-cafes"
    // h:graphicImage is discussed in the page templating section of
    // the general JSF2 tutorial (http://www.coreservlets.com/JSF-Tutorial/jsf2/).
    String path = String.format(template, num);
    return(path);
  }
}

Input page inplace.xhtml

This input page contains various types of input editable fields like text, colorpicker and editor which will be shown upon clicking the text.

image006

image007


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:p="http://primefaces.org/ui">
<h:head><title>p:inplace</title>
<link href="./css/extra-styles.css"
      rel="stylesheet" type="text/css"/>
</h:head>
<h:body>

<h1 class="ui-widget-header ui-corner-all" align="center">p:inplace</h1>
<br/>
<p:fieldset legend="Basic Version">
<h:form>
<h:panelGrid columns="2" class="formTable">
  Foreground:
  <p:inplace>
    <p:inputText value="#{colorPreferences.foreground}"/>
  </p:inplace>
  Background:
  <p:inplace>
    <p:inputText value="#{colorPreferences.background}"/>
  </p:inplace>
</h:panelGrid>
<p:commandButton action="#{colorPreferences.showSample}"
                 value="Show Sample" ajax="false"/>
</h:form>
</p:fieldset>
<br/>
<p:fieldset legend="Custom Labels">
<h:form>
  <p:inplace label="Foreground (#{colorPreferences.foreground})">
    <p:colorPicker value="#{colorPreferences.foreground}"/>
    <p:commandButton action="#{colorPreferences.showSample}"
                     value="Show Sample" ajax="false"/>
  </p:inplace><br/>
  <p:inplace label="Background (#{colorPreferences.background})">
    <p:colorPicker value="#{colorPreferences.background}"/>
    <p:commandButton action="#{colorPreferences.showSample}"
                     value="Show Sample" ajax="false"/>
  </p:inplace>
</h:form>
</p:fieldset>
<br/>
<p:fieldset legend="Editor (for Toggling)">
<h:form>
Image:
<p:inplace label="Random Internet Cafe" editor="true">
  <h:graphicImage url="#{imageBean.randomImage}"/>
</p:inplace>
</h:form>
</p:fieldset></h:body></html>

9. p:editor overview

  • Appearance and behavior– Large text area where user can enter and style text and it Uses the YUI rich text editor, which is used in Yahoo Mail.
  • Purpose: for collecting HTML text– Value is String that may contain HTML tags and When we output bean property, we must use escape=”false” to preserve the HTML tags.
  • Warning: security risk– Displaying unfiltered user data containing HTML can result in badly formatted pages if user enters unbalanced tags, images, and so forth.
  • Storing the results and displaying them later to other users lets users make malicious pages (with scripts, etc.) that are hosted on yoursite.
  • We are ignoring these risks in this example, but you should filter out some tags in real apps, especially if user data is stored and displayed to users other than the ones that entered the data.   See https://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29

Summary of Attributes

Syntax  :    <p:editor .../> 
  1. value: Should point to bean property of type String. String may contain HTML tags.
  2. controls : a space-separated list of the controls to show at the top of the editor. Options include bold, italic, underline, strikethrough, undo, redo, etc. Refer to Primefaces User’s Guide for a complete list. To prevent attacks, we almost certainly want to disallow the “source” option. Sadly, we can only list controls we do allow, not ones we disallow. This means that disallowing “source” means we will have to list all the others one at a time.

10. p:editor implementation

This is simple example to send message to Customer Service.

ManagedBean: MessageBean

This bean is having simple bean properties for collecting email address and message.

package net.javabeat.primefacescomp;
import javax.faces.bean.ManagedBean;

@ManagedBean
public class MessageBean {
  private String message, emailAddress;

  public String getMessage() {
    return(message);
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public String getEmailAddress() {
    return(emailAddress);
  }

  public void setEmailAddress(String emailAddress) {
    this.emailAddress = emailAddress;
  }

  public String showMessage() {
    return("show-message");
  }
}

Input page : editor.xhtml

image008


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:p="http://primefaces.org/ui">
<h:head><title>p:editor</title>
<link href="./css/extra-styles.css"
      rel="stylesheet" type="text/css"/>
</h:head>
<h:body>
<h1 class="ui-widget-header ui-corner-all" align="center">p:editor</h1>
<br/>
<p:fieldset legend="Message for Customer Service">
<h:form>
<h:panelGrid columns="3" class="formTable">
  Message:
  <p:editor value="#{messageBean.message}"
            required="true" id="message"
            requiredMessage="Message cannot be empty"/>
  <p:message for="message"/>
  Email address:
  <p:inputText value="#{messageBean.emailAddress}"
               required="true" id="email"
               requiredMessage="Email address required"/>
  <p:message for="email"/>
</h:panelGrid>
<p:commandButton action="#{messageBean.showMessage}"
                 value="Send to Customer Support"
                 ajax="false"/>
</h:form>
</p:fieldset>

</h:body></html>

PrimeFaces Input Elements Examples (58)

Comments

comments

Speak Your Mind

*