从百里香的角度来看,我可以确保以下代码可以正常工作。
<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;
}