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