繁体   English   中英

JSF selectOneMenu验证和Ajax渲染

[英]JSF selectOneMenu validation and ajax rendering

我在selectOneMenu上进行了验证,以防止用户在列表中选择“无”项目。

<h:selectOneMenu id="selectMenu" value="#{bean.selectedValue}" required="true" requiredMessage="Please select an item">
    <f:ajax render="toRender selectMenuMessage" listener="#{bean.onSelect}"/>
    <f:selectItem itemLabel="None" noSelectionOption="true"/>
    <f:selectItems value="#{bean.items}" var="item" itemValue="#{item.id}" itemLabel="#{item.label}"/>
</h:selectOneMenu>

我的面板在下面,并且只想在我的项目不是“无”时才显示它。 因此,当我选择“无”时,消息应呈现,面板消失。

<h:panelGroup id="toRender">
    <h:panelGrid rendered="#{bean.selectedValue == 0 ? false : true">
        ...
    </h:panelGrid>
</h:panelGroup>

它没有验证就可以工作,但是我不能同时做这两个工作。就像验证阻止了渲染一样。

有什么建议吗? 谢谢

我猜bean.selectedValue是一个整数,所以试试这个:

<f:selectItem itemValue="0" itemLabel="None" noSelectionOption="true"/>


编辑:抱歉,我认为您的问题有点误解了。
这里的问题是,如果您需要为selectOneMenu设置一个值,则该值为空时将不会提交。 并且,如果选择了带有noSelectionOption="true"的项目,则它将被视为空,因此不会提交任何值。 当您检查bean.selectedValue == 0selectedValue将永远不会为0(可能最初除外)为0,因为如上所述,当您选择值为0的项目时,它将不会被提交。
因此,您是对的,您的验证和bean.selectedValue == 0的检查不能一起使用。 我建议您只删除验证。
如果这不是您的选择,请向我解释为什么您需要它以这种方式进行更多详细说明。

我有一个回应,这不是解决方案,但这是实现此目标的另一种方式...

<h:selectOneMenu id="selectMenu" value="#{bean.selectedValue}">
    <f:ajax render="toRender selectMenuMessage" listener="#{bean.onSelect}"/>
    <f:selectItem itemLabel="None" noSelectionOption="true"/>
    <f:selectItems value="#{bean.items}" var="item" itemValue="#{item.id}" itemLabel="#{item.label}"/>
</h:selectOneMenu>

然后在豆子里

public void onSelect() {
    if(this.selectedValue != 0) {
        // Do smthg here
    } else {
        // Display error message
        UIComponent component = Outils.getFacesContext().getViewRoot().findComponent(":form:selectMenu");
        if(component != null) {   
            Outils.getFacesContext().addMessage(component.getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "Test msg"));
        }
    }       
}

这样,不会启动验证过程,而是在Bean中完成验证。

如果有人找到更好的东西,让我知道!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM