POSTing data with many to one relationship using Thymeleaf

后端 未结 1 911
[愿得一人]
[愿得一人] 2021-01-02 16:21

I have a simple model class Product which exhibits a many to one relationship with ProductCategory:

Product class:

@         


        
相关标签:
1条回答
  • 2021-01-02 16:44

    Note that I have changed the form method to POST.

    From thymeleafs perspective I can assure the below code should work.

    <form method="POST" th:action="@{/product/save}" th:object="${newProduct}">
        ....
        <select th:field="*{category}" class="form-control">
           <option th:each="category: ${productCategories}" th:value="${category.id}" th:text="${category.name}"></option>
        </select>
    

    Provided that your controller looks like this.

    @RequestMapping(value = "/product/save")
    public String create(Model model) {
        model.addAttribute("productCategories", productCategoryService.findAll());
        model.addAttribute("newproduct", new Product()); //or try to fetch an existing object
        return '<your view path>';
    }
    
    @RequestMapping(value = "/product/save", method = RequestMethod.POST)
    public String create(Model model, @Valid @ModelAttribute("newProduct") Product newProduct, BindingResult result) {
        if(result.hasErrors()){
            //error handling  
            ....
        }else {
            //or calling the repository to save the newProduct
            productService.save(newProduct);
            ....
        }
    }
    

    Update

    Your models should have proper getters and setters with the correct names. For example, for the property category You should have,

    public ProductCategory getCategory(){
        return category;
    }
    
    public void setCategory(productCategory category){
        this.category = category;
    }
    

    NOTE - I have not compiled this code, I got it extracted from my current working project and replace the names with your class names

    0 讨论(0)
提交回复
热议问题