The Java EE 6 Tutorial, Volume I

Rendering Components for Selecting Multiple Values

In some cases, you need to allow your users to select multiple values rather than just one value from a list of choices. The SelectMany components are used for this purpose. You can do this using one of the following component tags:

Figure 7–4 shows examples of these components.

Figure 7–4 Example SelectMany Components

Screen capture of check box set, drop-down menu, and
list box.

The SelectMany component allows the user to select zero or more values from a set of values. This section explains the h:selectManyCheckbox tag. The h:selectManyListbox tag and h:selectManyMenu tag are used in a similar way.

A list box differs from a menu in that it displays a subset of items in a box, whereas a menu displays only one item at a time when the user is not selecting the menu. The size attribute of the h:selectManyListbox tag determines the number of items displayed at one time. The list box includes a scroll bar for scrolling through any remaining items in the list.

The h:selectManyCheckbox tag renders a set of check boxes, with each check box representing one value that can be selected.

<h:selectManyCheckbox
    id="newsletters"
    layout="pageDirection"
    value="#{cashier.newsletters}">
    <f:selectItems
        value="#{newsletters}"/>
</h:selectManyCheckbox>

The value attribute of the h:selectManyCheckbox tag identifies the newsletters property of the Cashier backing bean. This property holds the values of the currently selected items from the set of check boxes. You are not required to provide a value for the currently selected items. If you don’t provide a value, the first item in the list is selected by default.

The layout attribute indicates how the set of check boxes are arranged on the page. Because layout is set to pageDirection, the check boxes are arranged vertically. The default is lineDirection, which aligns the check boxes horizontally.

The h:selectManyCheckbox tag must also contain a tag or set of tags representing the set of check boxes. To represent a set of items, you use the f:selectItems tag. To represent each item individually, you use a f:selectItem tag. The following subsection explains these tags in more detail.