Tuesday, October 18, 2016

Thymeleaf dropdown with selected option

Thymeleaf suggests dropdown creation as follows:

<select th:field="*{type}">
<option th:each="type : ${allTypes}"
             th:value="${type}"
             th:text="#{${'seedstarter.type.' + type}}">Wireframe
</option>
</select>

However, if you want to have a 'selected' option this would not work:

<select th:field="*{type}">
 <option th:each="type : ${allTypes}"
              th:value="${type}"
              th:text="#{${'seedstarter.type.' + type}}"
              th:selected="${myCondition}">Wireframe
</option>
</select>

Instead you should do:

<select name="type">
<option th:each="type : ${allTypes}"
             th:value="${type}"
             th:text="#{${'seedstarter.type.' + type}}"
             th:selected="${myCondition}">Wireframe
</option>
</select>