您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用Thymeleaf发布具有多对一关系的数据

使用Thymeleaf发布具有多对一关系的数据

从百里香的角度来看,我可以确保以下代码可以正常工作。

<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>

只要您的控制器看起来像这样。

@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);
        ....
    }
}

您的模型应该具有正确的具有正确名称的吸气剂和吸气剂。例如,对于category您应该拥有的属性

public ProductCategory getCategory(){
    return category;
}

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

- 我尚未编译此代码,我从当前的工作项目中提取了该代码,并将其名称替换为您的类名称

其他 2022/1/1 18:17:12 有466人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶