Steffen Kreutz Steffen Kreutz - 3 months ago 281
Java Question

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

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 object:

public class Ticket {

private Long id;

private String title;

private State state;

// Getters & setters

public static enum State {
OPEN, IN_WORK, FINISHED
}

}


In my controller I have a method that renders a form for this object:

@RequestMapping("/tickets/new")
public String showNewTicketForm(@ModelAttribute Ticket ticket) {
return "tickets/new";
}


The template looks like this:

<form th:action="@{/tickets}" method="post" th:object="${ticket}">
<input type="text" th:field="*{title}" />
<select></select>
</form>


Later it should be transformed to something like this:

<form action="/tickets" method="post">
<input type="text" name="title" />
<select name="state">
<option>OPEN</option>
<option>IN_WORK</option>
<option>FINISHED</option>
</select>
</form>


How can I create the select tag? The selected value should also be mapped to the ticket automatically so that I can do something like this in the controller:

@RequestMapping(value = "/tickets", method = RequestMethod.POST)
public String createTicket(@Valid Ticket ticket) {
service.createTicket(ticket);

return "redirect:/tickets";
}

Answer

You could do :

<select>
   <option th:each="state : ${T(com.mypackage.Ticket.State).values()}"
          th:value="${state}" 
          th:text="${state}">
   </option>
</select>
Comments