I was wondering what would be the best or easiest way to allow a user to select nothing in a selectOneMenu.
My example: I have a list of registered users and the administrator should be able to filter the list of displayed users by some criterias. These criterias, like the usertype (employee, customer, ...) can be chosen by selectOneMenus, like this:
<h:selectOneMenu value="#{myBean.selectedUsertype}" converter="#{usertypeConverter}">
<f:selectItems value={myBean.usertypes}" />
</h:selectOneMenu>
When the corresponding selectOneMenu is being backed by a list of POJOs using a converter, how can I add an item to the list indicating that the user didn't choose any specific item? Currently I have a dummy usertype object displaying the label "---", but this is causing several problems in other areas of my application and I don't think that this is the best solution.
Just explicitly set the select item value to null
.
<h:selectOneMenu value="#{bean.selectedItem}">
<f:selectItem itemValue="#{null}" itemLabel="--select--" />
<f:selectItems value="#{bean.availableItems}" />
</h:selectOneMenu>
No, an empty string like itemValue=""
is not sufficient. It really has to be null
. Otherwise you run into trouble as described in this Q&A: Using a "Please select" f:selectItem with null/empty value inside a p:selectOneMenu.
If the item happen to be required="true"
and you're using JSF 2.x, then you could add noSelectionOption="true"
to the select item. This is only useful if you also set hideNoSelectionOption="true"
on the selection component. It will then hide the empty option in the list once the enduser selects a different item, hereby making it impossible to re-select the empty option.
<h:selectOneMenu value="#{bean.selectedItem}" hideNoSelectionOption="true">
<f:selectItem itemValue="#{null}" itemLabel="--select--" noSelectionOption="true" />
<f:selectItems value="#{bean.availableItems}" />
</h:selectOneMenu>