Best way to add a “nothing selected” option to a selectOneMenu in JSF

会有一股神秘感。 提交于 2019-11-26 00:33:44

问题


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.


回答1:


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>



回答2:


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>



回答3:


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"


来源:https://stackoverflow.com/questions/11360030/best-way-to-add-a-nothing-selected-option-to-a-selectonemenu-in-jsf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!