Home How do you iterate through a List from a DTO in Thymeleaf?
Reply: 0

How do you iterate through a List from a DTO in Thymeleaf?

user1776 Published in May 21, 2018, 3:05 am

My project uses Spring Boot with JPA, MySQL and Thymeleaf. I can't seem to iterate inside the view through a list of objects stored inside a DTO which is passed as a model attribute to the view.

Here is the relevant bit of the DTO:

public class Form {
    private SimpleModel simpleModel = new SimpleModel();
    private List<Cities> listOfCities;
//......getters and setters

Here is the Cities model:

public class Cities {

    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id_city;

    private String name;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "id_country")
    private Countries id_country;
//getters and setters

Here is the controller:

public String simpleGet(Model model) {
    Form form = new Form();
    model.addAttribute("form", form);
    return "simple";

And finally, here is the view:

<form action="#" th:action="@{/simple}" method="POST" th:object="${form}">
 <input type="text"  th:field="*{simpleModel.userName}">
 <select name="id_city">
   <option th:each="city : ${listOfCities}" th:value="${city.id_city}" th:text="${city.name}"></option>
 <input type="submit"  value="Assign">

I have checked inside the controller after "form.setCities(citiesService.all());" by printing to the console in a for loop and the data is there, however in the view, I don't get anything, the select list is empty with no option elements. How can I access the data?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.249149 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO