spring thymeleaf alphbetically sort enum

时间:2018-02-17 12:16:34

标签: java spring thymeleaf

我有一个枚举:

public static enum States {

    SEL("Selangor"),
    WP("Wilayah Persekutuan"),      
    KEL("Kelantan"),
    LAB("Labuan"),
    PER("Perlis");  

    private String value;

    States(String val) {
        this.value = val ;
    }

    public String getValue() {
        return value;
    }       
}

这些值通过以下方式显示在Thymeleaf模板上:

<div class="col-xs-6 padding-sides-none">
  <div class="form-group col-xs-12 padding-sides-none">
    <label class="col-xs-2 padding-sides-none" style="margin-left:15px">State</label>
    <div class="col-xs-7 padding-sides-none">
      <select class="form-control selectpicker" data-live-search="true"
              style="width:300px;margin-left: 50px;">
        <option value="" selected disabled hidden>Please select a state</option>
        <option th:each="state : ${T(com.workspez.model.Accountant.States).values()}"
                th:value="${state}" th:text="${state.getValue()}">
        </option>
      </select>
    </div>
  </div>
</div>

我想按字母顺序显示值。可能吗?一种方法是手动排列枚举,但有没有办法对枚举列表进行排序? 感谢。

2 个答案:

答案 0 :(得分:1)

您可以在状态枚举中使用comparator来比较和排序枚举值,如下所示:

public enum States {
    SEL("Selangor"),
    WP("Wilayah Persekutuan"),      
    KEL("Kelantan"),
    LAB("Labuan"),
    PER("Perlis");  

    private String value;       
    States(String val){
        this.value = val ;
    }       
    public String getValue(){
        return value;
    }

    public static States[] getSortedValue(){
        States[] values = States.values();
        Arrays.sort(values,(s1,s2)->s1.getValue().compareTo(s2.getValue()));
        return values;
    }
}

在您的百万美元HTML中,只需调用getSortedValue方法即可按升序获取值:

<option th:each="state : ${T(com.crud.example.enums.States).getSortedValue()}"
th:value="${state}" 
th:text="${state.getValue()}">
</option>

答案 1 :(得分:0)

如何在组合框中获得所选值? 我做了:

<select th:field="*{currentAccountant.state}" class="form-control selectpicker"  data-live-search="true" style="width:300px;margin-left: 50px;"  >
                                      <option value="" selected disabled hidden>Please select a state</option>
                                     <option th:each="state : ${T(com.model.Accountant.States).getSortedValue()}"
                                        th:value="${state}" 
                                        th:text="${state.getValue()}">
                                    </option>
                                </select>

不再填充值。我删除th:field="*{currentAccountant.state}"然后填充