java 对 Thymeleaf 中的实体使用“选择”标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15227680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using 'select' tag with entities in Thymeleaf
提问by Filip Spiridonov
I am creating a form with the select tag that looks like this:
我正在创建一个带有 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
class of Spring Data JPA
helps to auto-convert selected id
to the entity Product
when I submit the form. The product
should also be not null (I am using @NotNull
on the product
field in the Version
class.
DomainClassConverter
class ofSpring Data JPA
有助于在我提交表单时将选定的自动转换id
为实体Product
。该product
也应该是不为空(我用@NotNull
的product
领域Version
类。
The problem that I have - when I come back to edit the data, the Product
is not selected.
我遇到的问题 - 当我回来编辑数据时,Product
没有选择。
If I modify the select
like this (th:field
and th:errors
): <-- p.s. is not a sad smile
如果我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>
then it becomes selected when I come back to edit it, but the validator doesn't work (product
is always instantiated, even if selected id is null
).
然后当我回来编辑它时它会被选中,但是验证器不起作用(product
总是被实例化,即使选择的 id 是null
)。
It looks like a very common scenario (selecting an entity from the list), but I cannot find any good looking example. Please share the secret knowledge.
它看起来像一个非常常见的场景(从列表中选择一个实体),但我找不到任何好看的例子。请分享秘密知识。
采纳答案by Filip Spiridonov
Solved. The problem existed because I had not overridden the equals()
and hashCode()
methods.
解决了。问题存在是因为我没有覆盖equals()
和hashCode()
方法。