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"/>
The workaround I use is setting the itemDisabled attribute and using this CSS:
But it needs to be fixed properly in JSF.
I solved my problem doing this
Building off of BalusC's answer, it's possible to do it without a backing bean list in newer versions of JSF (I'm using JSF 2.2):
I wrapped it in a composite component with some specific requirements. The part related to this question is using
f:selectItems
with a value of either[]
or[1]
. When your condition makes it use[]
then it will be omitted entirely, and when it uses[1]
then it puts in a single item with the values you want.<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.
The
<f:selectItem>
does not support therendered
attribute. Your closest bet is theitemDisabled
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.In case of
<h:selectOneMenu>
you're more dependent on whether the webbrowser supports hiding the disabled options via CSS: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?):Or, you could simply dynamically populate a
List<SelectItem>
in the backing bean based on the calculated conditions and bind it with<f:selectItems>
.You can wrap it into
ui:fragment
code:Then item will be rendered only when boolean codition is true.