Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

java - How to Post ArrayList of other Entity in Spring with Thymeleaf

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

At first I m not sure if this is needed

<div th:field="${post.categories}">

I think you can replace it with a simple div like this

    <form method="post" th:action="@{/post}">
        <div>
            <div th:each="category,iter : ${categories}">
                <input type="checkbox" id=${iter.index} name="categories" th:value="${category.text}">
                <label for=${iter.index}> The category</label><br>
            </div>
        </div>
        <input type="submit">
    </form>

Second I think you need the th: prefix from the value to get the value of the text property.

As you have it now, you are trying to add the index in the checkbox name. I would suggest to name all the checkboxes with the same name as is above, so on the post controller you will get an array of strings with the selected items

    @RequestMapping("/posts/new")
    public String newPost(Model model) {
        model.addAttribute("categories",
                Arrays.asList(
                        new Category("Category 1"),
                        new Category("Category 2"),
                        new Category("Category 3")));
        return "postForm";
    }

    @PostMapping
    @RequestMapping("post")
    public String saveOrUpdate(@RequestParam List<String> categories){
        categories.stream().forEach(System.out::println);
        return "postForm";
    }


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...