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?
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 thevalue
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 aMap
which in turn can also be used inf:selectItems
.Basic kickoff example:
with
and in result
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:
selectOneMenu
wiki pageWhat if the the value should be Integer and label String and both are needed in backing bean. Using Map in bean doesn't work because JSF interprets the map key as label. Ideally it would be a LinkedHashMap and search the text by a number.
Seems upside down to search number (value) by a text (key). What if some implementation of JSF adds extra space to test or letter case changes for some reason. Then the value is not found from map.
The following approach may also be useful in getting value and label using List <SelectItem>:
Here, facade, statesFacade fetches list of states from database/enterprise bean.
In view (xhtml page):
In the Managed Bean(applicationBean1.java):
Instead of Using Map I tried like this and it's perfectly working for me to get both ItemValue and ItemLabel in the same property by using "ItemValue" attribute in selectItems tag.How ever provided no extra commas in the ItemLabel(@asfas....i had the same problem u mentioned so i selected this approach).
Basically IssueDesc is String type in Bean Company
This will do the trick.
In your example, you would pass in the availableItems as 'list' and selectedItem as 'selection'. This method will return the label value corresponding to the selectedItem.