I want to display multiple items from database to Thymeleaf view, using HTML Form so that I can make a change and update to the database.
I was going to use th:field . but it occurred error. when I tried to use th:value. and It shows data.
<div th:each="item : ${courses}">
<form th:object="${item}">
<input th:field="*{name}" type="text" id="name" name="name" /> // error occur
</form>
</div>
error following.
Neither BindingResult nor plain target object for bean name 'item' available as request attribute
Whereas this below code works fine.
<div th:each="item : ${courses}">
<form th:object="${item}">
<input th:value="*{name}" type="text" id="name" name="name" /> // ok
</form>
</div>
Am I on the right track? Can you explain why? and the difference between field and value?
The bottom line is that you can only use th:object
and th:field
together on a base model attribute. That means you can't use it when iterating (because ${item}
doesn't exist on the model, it's a variable generated by the th:each
). The requirements are spelled out here:
Values for
th:object
attributes in form tags must be variable expressions (${...}
) specifying only the name of a model attribute, without property navigation. This means that an expression like${seedStarter}
is valid, but${seedStarter.data}
would not be.Once inside the
<form>
tag, no otherth:object
attribute can be specified. This is consistent with the fact that HTML forms cannot be nested.
th:field
sets the name
, id
, and value
of a field. So they are somewhat interchangeable but you should use th:field
whenever possible because it offers the extra integration with spring, and works on all kinds of input -- but these are really only useful when you are editing a single object on a page.
Since you have multiple objects you are iterating, you're going to have to manually set the name
, id
, and value
like you are doing.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments