I make a web application with Spring MVC and I have 3 tables with many-to-many relations. lectures--<lecture_groups>--groups. I can create a new lecture in a browser, but then I need to set groups for this lecture.
My idea was to choose all groups with checkbox and put them in an array. Further, I would have an id of the new lecture and array with property group's id and I would create several objects LectureGroup and save them into DB, but I don't know how to put checkbox values into an array.
I come up with something like this.
<body>
<form th:method="POST" th:action="@{/lectures/{id}/addGroups(id=${lectureId})}" th:object="${groupContainer}">
<h2>Choose groups for lecture:</h2>
<ul>
<li th:each="group : ${groups}">
<label th:for="${group.getId()}" th:text="${group.getName()}">Group</label>
<input type="checkbox" th:value="${group.getId()}" th:id="${group.getId()}" th:field=*{groupsId}"/>
</li>
</ul>
<input type="submit" value="Add!"/>
</form>
</body>
And methods in the controller:
@GetMapping("/{id}/addGroups")
public String selectGroups(Model model, @PathVariable("id") int lectureId) {
model.addAttribute("groupContainer", new ArrayList<Integer>());
model.addAttribute("lectureId", lectureId);
model.addAttribute("groups", groupService.getAllGroups());
return "lectures/lecture_groups";
}
@PostMapping("/{id}/addGroups")
public String addGroups(@PathVariable("id") int lectureId, @RequestParam("groupContainer") ArrayList<Integer> selectedGroups) {
for (Integer groupId : selectedGroups){
lectureGroupService.save(new LectureGroup(lectureId, groupId));
}
return "redirect:/lectures";
}
But it doesn't work. Please, give me advice on how to solve this problem.