I am creating a form with the select tag that looks like this:
<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.
The problem that I have - when I come back to edit the data, the Product is not selected.
If I modify the select like this (th:field and 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).
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.
Solved. The problem existed because I had not overridden the equals() and hashCode() methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With