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 <form:xxx> tags. You are going to need to use a plain-old <select> tag to pass the selected titleId back to the controller for processing. Unfortunately with a <select> 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 <select> tag this way:
<select id="titleInput" name="titleId">
<option value=""></option>
<c:forEach items="${titleList}" var="title">
<c:when test="${title.titleId== titleId}">
<option value="${title.titleId}" selected>${title.titleName}</option>
</c:when>
<c:otherwise>
<option value="${title.titleId}" >${title.titleName}</option>
</c:otherwise>
</c:forEach>
</select>
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.