我正在创建一个带有select标签的表单,如下所示:
<form th:object="${version}" method="post" class="form-horizontal">
...
<div class="control-group" th:classappend="${#fields.hasErrors('product')} ? 'error'">
<label class="control-label" for="product" th:text="#{version.product}">Product</label>
<div class="controls">
<select id="product" th:field="*{product}">
<option value="" th:text="#{common.select.prompt}"></option>
<option th:each="p : ${productList}" th:value="${p.id}" th:text="${p.name}"></option>
</select>
<span class="help-inline" th:errors="*{product}"></span>
</div>
</div>
...
</form>
当我提交表单时, DomainClassConverter
Spring Data JPA
类有助于将所选id
自动转换为实体Product
。 product
也应该不为空(我在@NotNull
类的product
字段中使用Version
。
我遇到的问题 - 当我回来编辑数据时,Product
未被选中。
如果我这样修改select
(th:field
和th:errors
):<-- p.s. is not a sad smile
<select id="product" th:field="*{product.id}">
<option value="" th:text="#{common.select.prompt}"></option>
<option th:each="p : ${productList}" th:value="${p.id}" th:text="${p.name}"></option>
</select>
<span class="help-inline" th:errors="*{product.id}"></span>
然后当我回来编辑它时会被选中,但验证器不起作用(product
总是被实例化,即使选择的id是null
)。
它看起来像一个非常常见的场景(从列表中选择一个实体),但我找不到任何好看的例子。请分享秘密知识。
答案 0 :(得分:3)
解决。存在问题是因为我没有覆盖equals()
和hashCode()
方法。