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

Roman Paolucci picture Roman Paolucci · Jun 9, 2016 · Viewed 53.7k times · Source

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++) {
        countryName.add(municipalities.get(i).getCountry().toString());
    }
    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 }"/>
</select>

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

Thanks in advance!

Answer

Hasitha Diluka picture Hasitha Diluka · Jun 9, 2016

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

Controller

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

Model

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

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

    getters and setters ...

}   

View

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