How to conditionally render an f:selectItem tag?

Rajat Gupta picture Rajat Gupta · Aug 3, 2011 · Viewed 37.7k times · Source

How can I specify a conditional rendering for an <f:selectItem> tag. I need to display <f:selectItem> options according to a specific user's status.

For example, I wanted something like:

<f:selectItem itemLabel="Yes! I need a girlfriend!"
             rendered="false(or some boolean condition)"
             itemValue="o1"/>

Answer

BalusC picture BalusC · Aug 3, 2011

The <f:selectItem> does not support the rendered attribute. Your closest bet is the itemDisabled attribute which still displays the item, but makes it unselectable. This is also supported in <f:selectItems>.

In case of <p:selectOneMenu> you can then just add some CSS to hide disabled items.

<p:selectOneMenu ... panelStyleClass="hideDisabled">
    <f:selectItem itemValue="1" itemLabel="one" />
    <f:selectItem itemValue="2" itemLabel="two" itemDisabled="#{some.condition}" />
    <f:selectItem itemValue="3" itemLabel="three" />
</p:selectOneMenu>
.ui-selectonemenu-panel.hideDisabled .ui-selectonemenu-item.ui-state-disabled {
    display: none;
}

In case of <h:selectOneMenu> you're more dependent on whether the webbrowser supports hiding the disabled options via CSS:

<h:selectOneMenu ... styleClass="hideDisabled">
    <f:selectItem itemValue="1" itemLabel="one" />
    <f:selectItem itemValue="2" itemLabel="two" itemDisabled="#{some.condition}" />
    <f:selectItem itemValue="3" itemLabel="three" />
</h:selectOneMenu>
select.hideDisabled option[disabled] {
    display: none;
}

The server side alternative is to bring in a JSTL <c:if> around the individual <f:selectItem> to contitionally add it to the view like this (make sure you're aware of how JSTL works in JSF: JSTL in JSF2 Facelets... makes sense?):

<f:selectItem itemValue="1" itemLabel="one" />
<c:if test="#{not some.condition}">
    <f:selectItem itemValue="2" itemLabel="two"  />
</c:if>
<f:selectItem itemValue="3" itemLabel="three" />

Or, you could simply dynamically populate a List<SelectItem> in the backing bean based on the calculated conditions and bind it with <f:selectItems>.