I have a simple form for adding a new teacher. I\'m using Spring
in my view to show a list of teacher\'s titles, but when I select an option
Your model includes an attribute title
that refers to a Title
class. This is not the same title
you are referring to in your form, which is actually a titleId
. Since the titleId
is not part of the modelAttribute
, it should be excluded from the
tags. You are going to need to use a plain-old tag to pass the selected
titleId
back to the controller for processing. Unfortunately with a tag, you can't just set the value attribute with JSTL, so you have to conditionally set the
seelcted
attribute of the option, based on the titleId
value (if it is set). If titleList
is a simple list of Title
objects, you can create your tag this way:
In your controller, the @RequestParam
annotation will pull the titleId
out of the submitted data. Since it is not part of the modelAttribute
, you need to make sure this gets added as a model attribute:
...
if (result.hasErrors()) {
if (titleId != null) {
model.addAttribute("titleId", titleId); // <--This line added
model.addAttribute("titleList", titleService.getAll());
Title title = titleService.get(titleId);
teacher.setTitle(title);
model.addAttribute("teacher", teacher);
return "addTeacher";
}
else {
model.addAttribute("titleList", titleService.getAll());
return "addTeacher";
}
}
...
Hopefully we got it this time.