仕事しててすごくハマった話。
type="hidden"でList
BookForm.java
@Getter @Setter public class BookForm implements Serializable { private List<Detail> details; @Getter @Setter public static class Detail implements Serializable { private Long id; private String name; private String passage; } }
index.html
<form class="form-horizontal case-entry" role="form" method="post" th:action="@{/requests/category(step=book-detail)}" th:object="${createForm}"> <div class="row"> <div class="col-md-12"> <fieldset> <th:block th:each="selectedBook: ${selectedBooks}"> <legend th:text="${selectedBook.name}"></legend> <table> <tr class="col-md-12"> <td> <div class="form-group" th:classappend="${#fields.hasErrors('all')}? has-error"> <input type="hidden" th:attr="name='details[' + __${selectedBookStat.index}__ + '].id'" th:value="${selectedBook.id}" /> <div class="col-md-6"> <input type="text" th:field="*{details[__${selectedBookStat.index}__].name}" class="form-control" /> </div> <div class="col-md-6"> <input type="text" th:field="*{details[__${selectedBookStat.index}__].passage}" class="form-control" /> </div> </div> </td> </tr> </table> </th:block> </fieldset> </div> </div> </form>
重要なのはth:attr="name='details[' + __${selectedBookStat.index}__ + '].id'"ですね!!!
th:attrは、任意の属性に値を設定する際に使います!
ちなみに、__は、プリプロセッシングといって通常の式よりも先に評価されます。