用于显示列表错误的表单绑定

2024-05-25

我有一个Product对象包含一个Set<Provider> providers。我在提供程序中注释了一个变量url with @NotEmpty现在,如果该字段为空,我想显示错误。 我不确定如何访问该字段providershasErrors方法得当。

Form:

<form action="#" th:action="@{/saveDetails}" th:object="${selectedProduct}" method="post">

  <!-- bind each input field to list (working) -->
  <input th:each="provider, status : ${selectedProduct.providers}"
         th:field="*{providers[__${status.index}__].url}" />

  <!-- all the time 'false' -->
  <span th:text="'hasErrors-providers=' + ${#fields.hasErrors('providers')}"></span>
  <span th:text="'hasErrors-providers[0].url=' + ${#fields.hasErrors('providers[0].url')}"></span>

  <!-- not working -->
  <span class="help-block" th:each="provider, status : ${selectedProduct.providers}" 
     th:if="${#fields.hasErrors('providers[__${status.index}__].url')}" 
     th:errors="${providers[__${status.index}__].url}">Error Url
  </span>

  <!-- print errors (just for testing purpose) -->
    <ul>
      <li th:each="e : ${#fields.detailedErrors()}">
        <span th:text="${e.fieldName}">The field name</span>|
        <span th:text="${e.code}">The error message</span>
      </li>
    </ul>

</form>

<ul>我收到每个错误providers[].url as e.fieldName。我认为它会有一些指数,比如providers[0].urlETC。 所以我的问题是,我如何访问该领域providershasErrors正确显示错误消息的方法。

EDIT

控制器:

@RequestMapping(value = "/saveDetails", method = RequestMethod.POST)
public String saveDetails(@Valid @ModelAttribute("selectedProduct") final Product selectedProduct,
                          final BindingResult bindingResult, SessionStatus status) {
    if (bindingResult.hasErrors()) {
        return "templates/details";
    }
    status.setComplete();
    return "/templates/overview";
}

您无法从Set使用它们的索引,因为集合没有排序。Set接口不提供基于索引获取项目的方法,所以这样做.get(index) to a Set会给你编译错误。使用List反而。这样,您就可以使用对象的索引来访问对象。

所以改变Set<Provider> providers to :

@Valid
List<Provider> providers;

不要忘记@Valid注释,以便它将向下级联到子对象。

另外,如果th:errors在表单内部,它应该使用选择表达式指向支持该表单的对象的属性(*{...})

<span class="help-block" th:each="provider, status : ${selectedProduct.providers}" 
    th:if="${#fields.hasErrors('providers[__${status.index}__].url')}" 
    th:errors="*{providers[__${status.index}__].url}">Error Url
</span>

EDIT

我发现您想要集体访问错误,而不是迭代它们。在这种情况下,您可以创建自定义 JSR 303 验证器。请参阅以下有用的代码片段:

Usage

@ProviderValid
private List<Provider> providers;

ProviderValid注解

//the ProviderValid annotation.
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ProviderValidator.class)
@Documented
public @interface ProviderValid {
    String message() default "One of the providers has invalid URL.";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

约束验证器

public class ProviderValidator implements ConstraintValidator<ProviderValid, List<Provider>>{

    @Override
    public void initialize(ProviderValid annotation) { }

    @Override
    public boolean isValid(List<Provider> value, ConstraintValidatorContext context) {

        //...
        //validate your list of providers here
        //obviously, you should return true if it is valid, otherwise false.
        //...

        return false;
    }
}

完成这些后,您可以轻松获得您在中指定的默认消息@ProviderValid注释如果ProviderValidator#isValid只需执行以下操作即可返回 false#fields.hasErrors('providers')

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

用于显示列表错误的表单绑定 的相关文章

随机推荐