Search code examples
javaspringspring-bootthymeleaf

How to populate a combo box with an ArrayList in Thymeleaf?


I have an ArrayList that contains objects, I want to populate the drop down box with each object (subject) in the arraylist.

At the moment my code is adding the ArrayList to the combo box however it's displaying everything in the ArrayList on each line rather than it displaying one subject per line. (See image below)

enter image description here

How do I get it to display each object in the arraylist?

My controller

@GetMapping("/addexam")
public String showExamForm(Model model) {
    Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
    String email = loggedInUser.getName();
    User user = userRepository.findByEmailAddress(email);
    ArrayList<String> subjects = new ArrayList<String>();
    for (Subject sub : user.getSubject()) {
        subjects.add(sub.getSubjectName());
    }
    model.addAttribute("subjects", subjects);
    return "addExam";
}

HTML file

<select class="form-control" id="subjectOrder" name="subjectOrder">
    <option value="">Select subject</option>
    <option th:each="Subject : ${subjects}" th:value="${subjects}" th:text="${subjects}"></option>
</select>

Solution

  • You're html section seems to be wrong as you're using the whole list at th:value and th:text (and so get all the entries in each line).

    Should be

    <option th:each="Subject : ${subjects}"
    th:value="${Subject}"
    th:text="${Subject}"></option>
    

    imo. Notice the use of ${Subject} rather than ${subject[s]}