jeudi 8 janvier 2015

How to retain values of mulitple checkboxes upon form submission using Spring?

I've looked at numerous posts on this topic but I am having a difficult time applying the solutions to my problem. I have a form that has multiple checkboxes and these checkbox values come from a list. When I submit the form I'm checking for errors and if the form has errors then it keeps the user on the same page. However, after I "submit" the form with errors, it removes my checked checkboxes. I'd like these to stay checked. Here's what I have for my code:


How the checkboxes are displayed on the form:



<div class="control-group">
<label class="control-label" for="moduleIds"><spring:message code="label.modules"/></label>
<div class="controls">
<c:forEach items="${modules}" var="module">
<label class="checkbox"><input type="checkbox" name="moduleIds" value="${module.id}" /> ${module.title}</label>
</c:forEach>
<form:errors path="moduleIds" cssClass="form-errors" />
</div>
</div>


Here's my controllers for loading the form then submitting it. The form is backed by the "assignTraining" object which will take the values of the checkboxes and add them to a list that is a field of the assignTraining object. "Modules" is the attribute that populates the checkboxes:



@RequestMapping(method = RequestMethod.GET, value = "/select")
public final String select(final ModelMap model) {
model.addAttribute("modules", moduleDao.findByDeletedFalse());
model.addAttribute("assignTraining", new AssignTraining());
return "userTraining/select";
}

/**
* Save new training for a user.
*
* @return The tile definition to view a user's training.
*/
@RequestMapping(method = RequestMethod.POST, value = "/save")
public final String save(final ModelMap model, @Valid AssignTraining assignTraining, BindingResult result) {
String formFile;

if (result.hasErrors()) {
formFile = "userTraining/select";
//add something here maybe?

} else {
List<Module> modules = moduleDao.findAll(new ArrayList<Long>(assignTraining.getModuleIds()));
List<TrainingEntry> trainingEntries = TrainingEntryUtil.scheduleTraining(assignTraining.getTmNumber(),
modules);
for (TrainingEntry entry : trainingEntries) {
trainingEntryDao.save(entry);
}
formFile = "redirect:/userTraining/view?tmNumber=" + assignTraining.getTmNumber();
}

return formFile;

}


Where I've commented "add something here?", I was thinking of setting a ModelAttribute of the selected checkbox values and then using that attribute in my jsp page, but I'm not sure where to start. Any help is much appreciated.





Aucun commentaire:

Enregistrer un commentaire