如何将布尔值设置为“是”或“否”h:selectOneRadio

时间:2012-02-08 03:42:06

标签: jsf-2

我在Tomcat 7上运行的JSF-2 Mojarra 2.0.8中有以下代码

<h:panelGrid  id="yesNoRadioGrid">
<h:panelGrid columns="2" rendered="#{user.yesNoRadioGridFlag}">
    <h:outputText id ="otherLbl" value="Select Yes or No"></h:outputText>
    <h:selectOneRadio id="yesNoRadio" value ="#{user.yesNoRadio}">
        <f:selectItems value="#{user.choices}"/>                    
        <f:ajax execute="@form" render="userDetailsGrid "></f:ajax>
    </h:selectOneRadio>
</h:panelGrid>
</h:panelGrid>      
<h:message for ="yesNoRadio"> </h:message>
<h:panelGrid  id="userDetailsGrid">
<h:panelGrid columns="2" rendered="#{user.yesNoRadio}">
    <h:outputLabel>Name :</h:outputLabel>
    <h:inputText id="customerName" value="#{user.customerName}"></h:inputText>
    <h:outputLabel>Salary: </h:outputLabel>
    <h:inputText id="customerSalary" value="#{user.customerSalary}"></h:inputText>
</h:panelGrid>
</h:panelGrid>

我的managedBean包含以下

private enum Choice {

    Yes, No; 
    } 
private Choice yesNoRadio;
public Choice[] getChoices() {
    return Choice.values(); 
    }
public Choice getYesNoRadio() {
    return yesNoRadio;
}
public void setYesNoRadio(Choice yesNoRadio) {
    this.yesNoRadio = yesNoRadio;
}

如何基于

中选择的布尔值(user.yesNoRadio)渲染我的'userDetailsGrid'

我通过在我的mangedbean中添加以下内容找到了一个workarround

private Boolean yesNoRadio;
public SelectItem[] getMyBooleanValues() {   
    return new SelectItem[] {    
    new SelectItem(Boolean.TRUE, "Yes"),   
    new SelectItem(Boolean.FALSE, "No")    
    };   
}  

并将我的观点更改为

<h:selectOneRadio id="yesNoRadio" value ="#{user.yesNoRadio}">
    <f:selectItems value="#{user.myBooleanValues}" />                   
    <f:ajax execute="@form" render="userDetailsGrid "></f:ajax>
</h:selectOneRadio>

2 个答案:

答案 0 :(得分:14)

在辅助bean中使用一个简单的布尔值:

private Boolean choice;
// getter and setter

在脸上:

<h:selectOneRadio id="yesNoRadio" value ="#{user.choice}">
  <f:selectItem itemValue="#{false}" itemLabel="No" />
  <f:selectItem itemValue="#{true}" itemLabel="Yes"/>
  <f:ajax execute="@form" render="userDetailsGrid "></f:ajax>
</h:selectOneRadio>
..
<h:panelGrid  id="userDetailsGrid">
  <h:panelGrid columns="2" rendered="#{user.choice}">
  ..
  </h:panelGrid>
  ..
</h:panelGrid>

答案 1 :(得分:4)

您也可以只检查rendered属性中的枚举值。枚举在EL中被评估为字符串,因此您可以进行简单的字符串比较。这样您就可以保留原始代码。

<h:panelGrid columns="2" rendered="#{user.yesNoRadio == 'Yes'}">

顺便说一下,您可能真的想使用execute="@this"代替execute="@form"(或者只是将其删除,默认为@this)。 execute="@form"将处理整个表单,因此也可以在您可能不需要的位置激活验证。