Search code examples
javaspringspring-bootspring-mvcthymeleaf

Dynamic fields thymeleaf list iteration


I'm getting a really weird error! while iterating on list, thymeleaf identified index as a property of my bean and not an index value!

<div th:each="phoneStat : *{phones}">
    <select th:field="*{phones[__${phoneStat.index}__].variety}">
        <option></option>
    </select>
    <div class=" input-field col s4">
        <input class="validate" th:field="*{phones[__${phoneStat.index}__].number}"
               th:id="${'phonenumber-'+ phones[__${phoneStat.index}__]}" type="text"/>
        <label th:for="${'phonenumber-'+ phones[__${phoneStat.index}__]}"> Mobile</label>
    </div>
</div>

What am I doing wrong here? Please help!

2015-06-15 15:48:25.453 ERROR 7764 --- [nio-8080-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "phoneStat.index" (/custom:89)] with root cause

org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 10): Property or field 'index' cannot be found on object of type 'com.ubleam.corporate.server.model.Phone' - maybe not public?

Solution

  • Actually when binding fields to a form, in order to acces to a list with th:each as the doc specifies, we should use two variables item and phoneStat:

    <div th:each="item, phoneStat : *{phones}">
        <select th:field="*{phones[__${phoneStat.index}__].variety}">
            <option></option>
        </select>
        <div class=" input-field col s4">
            <input class="validate" th:field="*{phones[__${phoneStat.index}__].number}"
                   th:id="${'phonenumber-'+ phones[__${phoneStat.index}__]}" type="text"/>
            <label th:for="${'phonenumber-'+ phones[__${phoneStat.index}__]}"> Mobile</label>
        </div>
    </div>