form select th:field and th:selected not working, how do you set default value?

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

form select th:field and th:selected not working, how do you set default value?

didier
Hi,
I've been trying to create an app with spring 4.3.9 + Thymeleaf 3.0.6.
Unfortunately I'm stucked at the select form object, as I can get it to select a default value.
I've been following this doc:
http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#dropdownlist-selectors
But didn't find a way to set a default select value/option, especially if you load an existing record (which already has an existing value). I found th:selected somewhere which sounded good to me but I doesn't seem to work ... with the select/option (at least with th:field).

I'm loading a "contact" object where the "address" object is embedded into contact and the "country" object is embedded into "address".  The select option values are populated correctly with this code, but th:selected is ignored and no default selected value is chose:
<form action="#" th:action="@{/contact/save}" th:object="${contact}" method="post">
... other input and form objects
....
<select th:field="address.country" class="form-control">
  <option th:each="country : ${allCountries}"
    th:value="${country.id}"
    th:text="${country.name}"
    th:selected="${contact.address.country.id}">
 </option>
</select>
</form

I also googled and found somewhere that I should use:
<select id="address.country" class="form-control"> insted of (select th:field=)
but without success, it doesn't work either.

I would really appreciate some help ... otherwise it makes it useless for our app. What am I missing here?

Thank you very much.
Didier
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: form select th:field and th:selected not working, how do you set default value?

didier
Hi,
I was able to fix the problem.
Here is what I'm using.
<select name="address.country" id="address.country" class="form-control">
        <option th:each="country : ${allCountries}"
               th:value="${country.id}"
               th:text="${country.name}"
               th:selected="${country.id == contact.address.country.id}">
       </option>
</select>

I had to get rid of the th:field and do a compare in th:selected.
Loading...