Best way to add a “nothing selected” option to a s

2019-01-01 03:48发布

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.

3条回答
旧人旧事旧时光
2楼-- · 2019-01-01 04:20

We can in primefaces (when we have to use <p:selectOneMenu... from some reason like using <p:ajax..) add the following empty item:

<f:selectItem itemValue="#{null}" itemLabel="--select--"  itemDisabled="#{Mybean.value ne null}" />

Note: In such case we don't need the following two tags:

hideNoSelectionOption="true"

and

noSelectionOption="true"
查看更多
余欢
3楼-- · 2019-01-01 04:33

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. If you also set hideNoSelectionOption="true" on the selection component, then it will 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>
查看更多
其实,你不懂
4楼-- · 2019-01-01 04:34

Add a single selectItem with null value;

<h:selectOneMenu value="#{bean.question}" required="true" requiredMessage="Please select a question">
    <f:selectItem itemValue="#{null}" itemLabel="Select" />
    <f:selectItems value="#{bean.questions}" />
</h:selectOneMenu>
查看更多
登录 后发表回答