【问题标题】:Omit validation when making change on selectOneMenu with ajax使用 ajax 对 selectOneMenu 进行更改时省略验证
【发布时间】:2019-11-27 13:16:22
【问题描述】:

我有一个带有 ajax 的表单中的 selectOneMenu,用于在触发时更新单独的组件。此菜单还使用验证。菜单中的第一项为空,如果该项为空,验证确保您无法提交表单。但是,我确实希望用户能够选择空项目,并将我的支持 bean 中该项目的值设置为空。但是,当用户选择 null 项时,设置不会发生,因为首先发生验证失败并引发异常,从而阻止在我的支持 bean 中将值设置为 null。

这是我的代码

<h:form>
...
   <p:selectOneMenu value="#{myBean.container}">
      <f:selectItem itemLabel="Select One" itemValue=#{null} />
      <f:selectItems value="#{myBean.getContainerItems()}" />
      <p:ajax event="change" update="containerNumSection" />
      <f:validateRequired />
   </p:selectOneMenu>
...
</h:form>

当用户在保持验证的同时选择 null 项时,有什么方法可以将我的支持 bean 中的值设置为 null?

【问题讨论】:

  • 如果没有f:validateRequired,null 甚至不会提交,是吗? (经测试 PF 7.0)
  • 不,它不提交,这就是我想要的,但是每次由于 ajax 而更改值时,也会发生验证。这可以防止在我的支持 bean 中将值设置为 null
  • 而且它甚至不会在没有 ajax 的情况下提交,是吗? h:selectonemenu 有效吗?

标签: jsf primefaces


【解决方案1】:

我发现了一种使用自定义验证方法的有点肮脏的解决方法,该方法能够区分 selectOneMany 更改或提交按钮被按下的情况:

<h:form>
    <p:selectOneMenu id="select" value="#{myBean.stringVal}"
        validator="#{myBean.validateSelection}">
        <f:selectItem itemLabel="nothing" itemValue="#{null}" />
        <f:selectItem itemLabel="a" itemValue="a" />
        <f:selectItem itemLabel="b" itemValue="b" />
        <p:ajax update="@form" process="@this"/>
    </p:selectOneMenu>

    <p:commandButton value="submit" update="@form" process="@form">
        <f:param name="selectionRequired" value="true"/>
    </p:commandButton>

    <h:message for="select" />
    <h:outputText value="#{myBean.stringVal}" />
</h:form>

如果用户按下提交按钮,名为“selectionRequired”的请求参数将设置为“true”。如果是这种情况,验证方法将委托给javax.faces.validator.RequiredValidator.validate() 方法,否则它什么也不做。

MyBean.validateSelection:

public void validateSelection(FacesContext context, UIComponent component, Object value) {
    String selectionRequired = FacesContext.getCurrentInstance().getExternalContext()
            .getRequestParameterMap()
            .get("selectionRequired");
    if (Boolean.valueOf(selectionRequired)) {
        new RequiredValidator().validate(context, component, value);
    }
}

我必须启用 javax.faces.VALIDATE_EMPTY_FIELDS 才能使其工作,否则在选择 #{null} 时根本不会调用 validateSelection 方法。

web.xml:

<context-param>
    <param-name>javax.faces.VALIDATE_EMPTY_FIELDS</param-name>
    <param-value>true</param-value>
</context-param>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 2014-11-20
    • 1970-01-01
    相关资源
    最近更新 更多