How to display all possible enum values in a dropdown list using Spring and Thymeleaf?
You could do:
<select>
<option th:each="state : ${T(com.mypackage.Ticket.State).values()}"
th:value="${state}"
th:text="${state}">
</option>
</select>
In addition, if you want to separate the enum ordinal name from the string displayed in the GUI, add additional properties, for example a displayName:
public static enum State {
OPEN("open"),
IN_WORK("in work"),
FINISHED("finished");
private final String displayName;
State(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
}
And in the html file:
<select>
<option th:each="state : ${T(com.mypackage.Ticket.State).values()}" th:value="${state}" th:text="${state.displayName}"></option>
</select>
This will present the displayName to the user and allows you to silently change this strings later without refactoring the code. You may add more properties like th:title this way.