Reputation: 21
I have multiple objects inside a list and wanted to create a form for every object in that List (the user can only submit one object at once). But as soon as I use th:field instead of name and value I get an exception. Maybe someone can help me. It only happens when using the th:each; if I pass in a single object to the form it works... I reduced the problem to the minimum so its more readable :)
Exception:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'o' available as request attribute
Controller class:
@Controller
public class TestController {
@GetMapping("/objectlisttest")
public ModelAndView getObjectListTest() {
ModelAndView mv = new ModelAndView("objectlisttest");
List<DataObject> objects = new ArrayList<>();
for (int i = 0; i < 5; i++) {
DataObject o = new DataObject();
o.setText("Dataobject");
objects.add(o);
}
mv.addObject("objects", objects);
return mv;
}
@PostMapping("/objectlisttest")
public ModelAndView editObjectListTest(DataObject o, BindingResult br) {
System.out.println(o);
return getObjectListTest();
}
public static class DataObject {
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
}
View:
<div th:each="o : ${objects}">
<form th:object="${o}" th:action="@{/objectlisttest}" method="POST">
<label>Text<input type="text" th:field="*{text}"></label>
<input type="submit">
</form>
</div>
Thanks in advance
EDIT: Changing the View to
<div th:each="o : ${objects}">
<form th:object="${o}" th:action="@{/objectlisttest}" method="POST">
<label>Text<input type="text" th:value="*{text}" th:name="text"></label>
<input type="submit">
</form>
</div>
works. But th:field would be much nicer...
Upvotes: 1
Views: 733
Reputation: 57381
It expects to have "o" object in model. If you call
mv.addObject("o", someObject);
The error disappear I think but there would be a conflict between "o" in model and "o" as a loop variable.
I would say it's not good idea to add multiple forms with the same reference to model (all the forms has th:object="${o}"
).
You should redesign the logic. Either place each object separately in the model or create just one form to keep list.
Upvotes: 0