Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'select' tag with entities in Thymeleaf

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.

like image 246
Filip Spiridonov Avatar asked Oct 22 '22 15:10

Filip Spiridonov


1 Answers

Solved. The problem existed because I had not overridden the equals() and hashCode() methods.

like image 61
Filip Spiridonov Avatar answered Oct 28 '22 19:10

Filip Spiridonov