I have a domain object that has an enum property and I want to display a dropdown list with all possible enum values in the form for this object. Imagine the following objec
You could do:
<select>
<option th:each="state : ${T(com.mypackage.Ticket.State).values()}"
th:value="${state}"
th:text="${state}">
</option>
</select>
this worked for me:
Java:
public enum RoleEnum {
SUPER_ADMIN("SUPER_ADMIN"),
RESTAURANTE_ADMIN("RESTAURANTE_ADMIN");
private final String roleCode;
private RoleEnum(String roleCode) {
this.roleCode = roleCode;
}
}
Thymeleaf:
<select class="form-control" id="val-skill" name="role_id">
<option th:each="role : ${T(com.users.enumeration.RoleEnum).values()}" th:value="${role}" th:text="${role}"></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.