1

To display global errors created with Spring MVC with Thyme Leaf, I tried the example given at http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#global-errors:

That, is:

<div th:if="${#fields.hasGlobalErrors()}">

and

<ul th:if="${#fields.hasErrors('global')}">

and

<div th:if="${#fields.hasGlobalErrors()}">

When I add them to my HTML, the page won't even render, nevermind about submitting the form. All the examples result in:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#fields.hasErrors('global')"

I tried this with v2.1.4 and v.2.1.3 and got the same error. Bug or am I doing something wrong?

Yes, the tags are all closed and properly formed. Yes, this code was within a form. Yes, all the other aspects of the form work without the global error check.

Here is a short version of broken HTML:

<form action="search.html" th:action="@{/auto/search}">
<p th:if="${#fields.hasErrors('global')}" th:errors="*{global}">
    Incorrect date
</p>
<input type="text" th:field="${command.stockNumber}" />
<select th:field="*{command.startYear}">
    <option value="" th:each="year : ${modelYears}" th:value="${year}"
            th:text="${year}"></option>
</select>
</form>

And the controller..

@RequestMapping(value = "/auto/search", method = RequestMethod.POST)
public String search(@Validated
                     @ModelAttribute("command")
                     AutoSearchCommand autoSearchCommand
                     BindingResult result, Model model) {
    return "search";
}
Jason Hendriks
  • 89
  • 1
  • 1
  • 9

1 Answers1

5

Solved:

th:object is needed in a tag preceding to the global error check. Unfortunately, this isn't mentioned in the Spring Thyme Leaf tutorial. Presumably, there's a default form name somewhere which I've overridden in my controller.

Adding the tag in results in this working html:

<form action="search.html" th:action="@{/auto/search}">
<div th:object="${command}" th:remove="tag">
    <p th:if="${#fields.hasErrors('global')}" th:errors="*{global}">
        Incorrect date
    </p>
</div>
<input type="text" th:field="${command.stockNumber}" />
<select th:field="*{command.startYear}">
    <option value="" th:each="year : ${modelYears}" th:value="${year}"
            th:text="${year}"></option>
</select>
</form>

.. Where "command" is the name of the form bean in the controller.

This thread helped me figure it out.

Community
  • 1
  • 1
Jason Hendriks
  • 89
  • 1
  • 1
  • 9
  • You should be able to access it outside the form or without `th:object="${command}"` by using the syntax `th:errors="${command.global}"`. See [http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#displaying-errors-outside-forms] – phn Oct 04 '16 at 11:51