How to conditionally render an f:selectItem tag?

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>.


The workaround I use is setting the itemDisabled attribute and using this CSS:

select option[disabled] { display: none; }

But it needs to be fixed properly in JSF.


<c:if> for me is also not working if it depends on the repeated variable of a ` component (on first build phase it works but using ajax and updating the collection of the for-each it fails, showing some items twice and others not)

this is really one big issue in JSF. Disabling is not always an option, and this way much more code is necessary in the bean to address such "easy" things.