我有Project
个对象,其中包含带有Roles
对象的列表Role
。我想使用表单编辑项目。此表单需要包含角色清单。所以我将Project
对象与th:object
绑定在一起。现在,当用户选中复选框并保存时,它会因错误而失败。
表单以呈现复选框
<ul class="checkbox-list">
<li th:each="role,stat : ${allRoles}">
<input type="checkbox" th:value="${role.id}" th:field="*{roles[__${stat.index}__].id}"/>
<span class="primary" th:text="${role.name}"> Developer</span>
</li>
</ul>
项目对象
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
int id;
String name;
String description;
private String status;
private String slug;
@ManyToMany
List<Role> roles = new ArrayList<>();
@ManyToMany
List<Collaborator> collaborators = new ArrayList<>();
................
................
}
角色对象:
@Entity
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY )
private int id;
private String name;
.............
.............
.............
}
相关控制器方法
@RequestMapping("/edit-project/{slug}")
public String editProjectFromSlug(@PathVariable String slug,Model model) {
Project project = projectService.findProjectBySlug(slug);
List<Role> allRoles = roleService.getAllRoles();
//Two objects are added to the model
model.addAttribute("project",project);
model.addAttribute("allRoles",allRoles);
return "edit_project";
}
@RequestMapping(value = "/save-project", method = RequestMethod.POST)
public String saveProject(@ModelAttribute Project project,Model model){
projectService.saveProject(project);
return "redirect:/projects";
}
我已经提到了多个答案,例如this。他们都没有工作。代码位于此github repo。请帮我修复此错误。