How to display all possible enum values in a dropdown list using Spring and Thymeleaf?

前端 未结 3 1856
忘了有多久
忘了有多久 2020-12-30 22:51

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

相关标签:
3条回答
  • 2020-12-30 22:55

    You could do:

    <select>
        <option th:each="state : ${T(com.mypackage.Ticket.State).values()}"
                th:value="${state}"
                th:text="${state}">
        </option>
    </select>
    
    0 讨论(0)
  • 2020-12-30 22:59

    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>
    
    0 讨论(0)
  • 2020-12-30 23:15

    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.

    0 讨论(0)
提交回复
热议问题