How to get both label and value from f:selectItems

SomeFatMan picture SomeFatMan · Jun 29, 2010 · Viewed 95k times · Source

I am working on a JSF page which has a dropdown based on List<SelectItem>:

<h:selectOneMenu value="#{bean.selectedItem}">
    <f:selectItems value="#{bean.availableItems}" />
</h:selectOneMenu>

I need to get both the value and label of the currently selected item. Right now I only get the value. How can I get the label, too?

Answer

BalusC picture BalusC · Jun 29, 2010

You can't. That's just how HTML works. You know, JSF is a HTML code generator. The JSF <h:selectOneMenu> generates a HTML <select><option> . The HTML <select> element will only send the value attribute of the selected <option> element. It will not send its label.

But that shouldn't be a big issue. You namely already know both the value and label in the server side, inside the #{bean.availableItems}. All you need to do to get the associated label is to get it by the value as key. I suggest to make it a Map which in turn can also be used in f:selectItems.

Basic kickoff example:

public class Bean {
    private String selectedItem; // +getter +setter
    private Map<String, String> availableItems; // +getter

    public Bean() {
        availableItems = new LinkedHashMap<String, String>();
        availableItems.put("value1", "label1");
        availableItems.put("value2", "label2");
        availableItems.put("value3", "label3");
    }

    public void submit() {
        String selectedLabel = availableItems.get(selectedItem);
        // ...
    }
}

with

<h:selectOneMenu value="#{bean.selectedItem}">
    <f:selectItems value="#{bean.availableItems.entrySet()}" var="entry"
        itemValue="#{entry.key}" itemLabel="#{entry.value}" />
</h:selectOneMenu>

and in result

<p>Selected label is #{bean.availableItems[bean.selectedItem]}</p>

An alternative is to wrap both name and value in a javabean object representing an entity and set the whole object as value, via a converter.

See also: