I have a class Post
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany
@JoinTable(name = "post_category",
joinColumns = @JoinColumn(name = "post_id"),
inverseJoinColumns = @JoinColumn(name = "category_id"))
private List<Category> categories = new ArrayList<Category>();
I have also other String fields but that is not important. Category is:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany(mappedBy = "categories")
private List<Post> posts = new ArrayList<>();
I want to post a Post entity. But I have a problem with Category field in Post class.
<div th:field="${post.categories}">
<div th:each="category,iter : ${categories}">
<input type="checkbox" id=${iter.index} name=${"category"+"["+iter.index+"]"} value=${category.text}>
<label for=${iter.index}> The category</label><br>
</div>
</div>
I want to have a list of checkboxes with categories in post form html. If the category is clicked (checked) I want it to be added to category List in the Post Class. However it doesn't happen. In controller class when I get the Post class returned after submitting, I don't even have categories in the fields from form. These are my requests in Controller:
@RequestMapping("/posts/new")
public String newPost(Model model){
model.addAttribute("post", new PostForm());
model.addAttribute("categories", categoryRepository.findAll());
return "postForm";
}
@PostMapping
@RequestMapping("post")
public String saveOrUpdate(@ModelAttribute PostForm postForm){
PostForm savedPost = postService.savePostForm(postForm);
return "redirect:/post/show/" + savedPost.getId();
}
Somebody has any idea how to make a list of checkboxes to click and then add the categories to Post entity?
Thanks
question from:
https://stackoverflow.com/questions/65646577/how-to-post-arraylist-of-other-entity-in-spring-with-thymeleaf 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…