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

73,411

Solution 1

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>

Solution 2

First thank to your question and answer! I've done with this solution.

My Model

@Entity
@Table(name = "test")
public class Test {

    @Id
    private String testCode;
    private String testName;
    private int price;

    public Test() {}

    public Test(String testCode, String testName, int price) {
        this.testCode = testCode;
        this.testName = testName;
        this.price = price;
    }

    public String getTestCode() {
        return testCode;
    }

    public String getTestName() {
        return testName;
    }

    public int getPrice() {
        return price;
    }
}

My View

    List<Test> test = new ArrayList<>();
    model.addAttribute("test", test);
    List<Test> tests = testRepository.findAll();
    model.addAttribute("tests", tests);

My HTML

<div class="col-lg-3" th:object="${test}">
    <select class="form-control" id="testOrder" name="testOrder">
        <option value="">Select Test Order</option>
        <option th:each="test : ${tests}"
                th:value="${test.testCode}"
                th:text="${test.testCode}+' : '+${test.testName}"></option>
    </select>
</div>

My Result

Image - tymeleaf dropdown from model

Solution 3

For generating dropdown for the list of String returned in model you just need to use these lines. You don't need to create any model class with extra getter and setter methods. Your code is correct, you just missed the variable name for storing the value returned in countryName list in th:each.

<select th:field="*{countryName}">
<option value="">Select Country</option>
<option th:each="country : ${countryName}" th:value="${country}" th:text="${country}"></option>
</select>
Share:
73,411

Related videos on Youtube

Roman Paolucci
Author by

Roman Paolucci

Updated on December 18, 2020

Comments

  • Roman Paolucci
    Roman Paolucci over 3 years

    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!

  • olammy
    olammy about 6 years
    Your List<Test> test = new ArrayList<>(); is doing nothing, therefore, there is no need to write such a bogus code. These lines of code will however do the trick for you: List<Test> tests = testRepository.findAll(); model.addAttribute("tests", tests); Also, it is good to use your service instead of using the repository.
  • naXa stands with Ukraine
    naXa stands with Ukraine over 5 years
    th:text="select operator" gives error "TemplateProcessingException: Could not parse as expression". +1 anyway ;)
  • Richard Bradley Smith
    Richard Bradley Smith about 4 years
    I got it to work as Raneer said but it wasn't easy. I think the complications come in depending on how one arrives at the original list that creates the array list.
  • Eamon Mac
    Eamon Mac almost 4 years
    Do you have to use a list?
  • Thanongsak Chamung
    Thanongsak Chamung almost 4 years
    Yes I user a list.
  • Eamon Mac
    Eamon Mac almost 4 years
    Ok, and for POST, how do you save the selected item from dropdown to database?
  • Aakash Patel
    Aakash Patel over 3 years
    If list size is only 1, how can i select default first value onload?
  • Justin Jones
    Justin Jones over 2 years
    How would we an additional option if the th:field value isn't contained in the country list? Thanks