Roman Paolucci Roman Paolucci - 10 months ago 95
HTML Question

How do I populate a drop down with a list using thymeleaf and spring

I need to populate a drop down with all the values within a list of strings.

Controller Class

@RequestMapping(value = "/generateIds", method = RequestMethod.GET)
public String launchPage(Model model) {
List<Municipality> municipalities = rCountryService.finaAllMunicipalities();
//assume the list is populated with values
List<String> countryName = new ArrayList<String>();
for(int i=0; i<municipalities.size(); i++){
model.addAttribute("countryName ", countryName );

return "generateIds";

I didn't know where to start for the HTML so I started with this

<select th:field="*{countryName }">
<option value="default">Select a country</option>
<option th:each="${countryName }" th:value="${countryName }"th:text="${countryName }"/>

What should my html/controller look like to add all of the elements of the list as drop down options?

Thanks in advance!

Answer Source

This is how I populate the drop down list.I think it may help to you get some idea about it.


List<Operator> operators =  operatorService.getAllOperaors()
model.addAttribute("operators", operators);


  @Table(name = "operator")
  public class Operator {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @NotBlank(message="operator Name cannot be empty")
    @Column(name = "operator_name", nullable = false)
    private String operatorName;

    getters and setters ...



<div class="form-group blu-margin">
    <select class="form-control" th:field="${operator.opeId}"  id="dropOperator">
    <option value="0" th:text="select operator" ></option>
    <option th:each="operator : ${operators}" th:value="${}" th:text="${operator.operatorName}"></option>