Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

jsf - How to conditionally render an f:selectItem tag?

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"/>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...