Thanthla
Thanthla

Reputation: 586

Thymeleaf: Iterate over enum values and use them in a list filter

I am struggling using enum values in list filters in Thymeleaf.

I know how to iterate over enum values and how to compare them against constant values. However, I want to compare it against a 'variable' value. How can I achieve it?

In my example below, I want to iterate trough all colors (enum) and then filter a list of cars by the current color enum and display their names.

How do I specify the list filter in the second <div> correctly?

<div th:each="currentColorEnum : ${T(de.my.enum.color).values()}">
    <div th:each="currentCar, carStatus : ${model.carList.?[#this.colorEnum eq __${currentColorEnum}__]}">                  
        <textarea th:field="*{carList[__${carStatus.index}__].carName}"></textarea>
    </div>
</div>

Current error message:

org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'red' cannot be found on object of type 'de.my.class.car' - maybe not public or not valid?

Upvotes: 0

Views: 1300

Answers (1)

Metroids
Metroids

Reputation: 20487

No need for preprocessing in this case. It's failing because ${model.carList.?[#this.colorEnum eq __${currentColorEnum}__]} resolves to ${model.carList.?[#this.colorEnum eq red]}. Which means it looking for cars where car.colorEnum == car.red -- hence the error field 'red' cannot be found on object of type 'de.my.class.car'.

Your Thymeleaf should look something like:

<div th:each="currentColorEnum : ${T(de.my.enum.color).values()}">
    <div th:each="currentCar, carStatus : ${model.carList.?[colorEnum eq #root.currentColorEnum]}">                  
        <textarea th:field="*{carList[__${carStatus.index}__].carName}"></textarea>
    </div>
</div>

Upvotes: 2

Related Questions