Using the 'select' tag with objects in Thymeleaf

I am creating a form with a 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>

DomainClassConverterthe class Spring Data JPAhelps to automatically convert the selected idto an object Productwhen I submit the form. Productshould also be non-null (I use @NotNullthe field Productin the class Version.

The problem that I have is that when I return to edit the data, it is Productnot selected.

If I change selectthis ( th:fieldand 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 return to edit it, but the validator does not work ( Productalways created even if the selected id is equal null).

( ), . , .

+5
1

. - , equals() hashCode().

+2

All Articles