Saturday, July 28, 2007

Selection Input for JSF Forms

Supposing the client for the timecard utility sends us two new requirements - that users should have an option of entering time as 24-hour or 12-hour format, and be able to review and modify up to 4 previous weeks in addition to the current week. In HTML, this would mean using radio buttons for the time format and a dropdown list for which week is being viewed/modified.
In JSF, you can use any of <h:selectBooleanCheckBox>, <h:selectManyCheckBox>, <h:selectBooleanListBox>, <h:selectManyMenu>, <h:selectOneListBox>, <h:selectOneMenu>, or <h:selectOneRadioButton>. To implement the requirements specified, we use <h:selectOneRadioButton> for radio buttons and <h:selectOneMenu> for the dropdown list.
Fortunately, JSF has the same mechanism for using these components. You create a class that returns SelectItem[] objects, and use it in both the JSP (to populate the components) and the managed bean. The thing to be careful about is to put components that are supposed to be updated together in their own form elements. Only those elements are updated when a button is clicked.

To start with, we create a new Java class in our project that holds the options. Here's the source code for Options.java. It declares the options we need and appropriate getters/setters. It also has a temporary routine to generate the 5 weeks needed. This method can be extended to read this data from a database.
The managed bean can then add attributes that use the options selected in the form. Here's the sources for Timecard2.java. The JSF configuration file would need to be updated with navigation rules (new faces-config.xml) for the options, and the main display JSP updated to show the appropriate components (here's index.java). After you deploy the application, you should have something that looks like this:

With this new build, a user can choose what format to enter time as, and which week to view by selecting the appropriate. This example demonstrates how easily a JSF application can be extended. It also begins cracking at the power of the JSF framework - there's much much more you can do with this technology.