I've got a Product
object that contains a Set<Provider> providers
. I've annotated within the Provider a variable url
with @NotEmpty
and now I want to display a error, if this field is empty.
I'm not sure how I can access the field providers
within the hasErrors
method properly.
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>
Within the <ul>
I receive for each error providers[].url
as e.fieldName
. I thought it would be having some indices like providers[0].url
etc.
So my question is, how can I access the field providers
within the hasErrors
method properly to display the error messages.
EDIT
Controller:
@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";
}