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

jvG*_*jvG 8 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>
Run Code Online (Sandbox Code Playgroud)

我的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;
}
Run Code Online (Sandbox Code Playgroud)

如何根据在中选择的布尔值(user.yesNoRadio)渲染我的'userDetailsGrid'

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

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

并改变我的观点

<h:selectOneRadio id="yesNoRadio" value ="#{user.yesNoRadio}">
    <f:selectItems value="#{user.myBooleanValues}" />                   
    <f:ajax execute="@form" render="userDetailsGrid "></f:ajax>
</h:selectOneRadio>
Run Code Online (Sandbox Code Playgroud)

Mat*_*ndy 16

在您的支持bean中使用一个简单的布尔值:

private Boolean choice;
// getter and setter
Run Code Online (Sandbox Code Playgroud)

在脸上:

<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>
Run Code Online (Sandbox Code Playgroud)


Bal*_*usC 5

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

<h:panelGrid columns="2" rendered="#{user.yesNoRadio == 'Yes'}">
Run Code Online (Sandbox Code Playgroud)

顺便说一句,您可能真的想使用execute="@this"而不是execute="@form"(或者只是将其完全删除,默认情况下@this已经使用)。在execute="@form"将处理整个形式,因此也很火验证在你的身边也许不想要的。