5

Thymeleaf multiple select on list on an object

I am using Thymeleaf and Spring MVC and I want to do a multiple select like this:

<form action="#" th:object="${promotion}" th:action="@{/promotion/add}" method="post">

<select th:field="*{products.id}" th:value="*{products.id}"  multiple="multiple" >
  <optgroup th:each="c : ${categories}" th:label="${c.name}">   
     <option th:each="p : ${c.products}" th:value="${p.id}" th:text="${p.name}" />
  </optgroup>
</select>
</form>

I have this object in the form

public class Promotion implements Serializable{
    private static final long serialVersionUID = 1L;
    private int id;
    private String name;
    private List<PromoProduct> products;
}

public class PromoProduct implements Serializable {
    private static final long serialVersionUID = 1L;
    private int id;
    private List<Integer> products;
    private int amount;
}

With this code I get the following error message:

org.springframework.web.util.NestedServletException: Request processing failed;
    nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "products.id" .

And I would like to get the selected data on id variable (inside products list). Could I do that? I don't know if this is possible, and if it is how could reach to id variable inside products object?

soufrk
  • 825
  • 1
  • 10
  • 24
Zuri
  • 312
  • 3
  • 18
  • Have you tried the above code? What is the output/error? Can u make a jsfiddle of how your select dropdown should look like? – Lucky Apr 21 '16 at 12:25
  • With this code I get the following error message: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "products.id" . I understand that as product is a list it can't get it. – Zuri Apr 21 '16 at 12:36
  • You don't need the th:value in your select tag as the th:field will fill the values automatically. – Lucky Apr 21 '16 at 12:38
  • Yes, I know it, but without th:value I get the same message too. – Zuri Apr 21 '16 at 12:53

1 Answers1

1

Shortly - products is the List, so it don't have field id. You need to create the PropertyEditor to realize the behaviour you want.
Nice answer given by @tom-verelst in thymeleaf multiple selected on edit. Please check it.

Community
  • 1
  • 1
sanluck
  • 1,544
  • 1
  • 12
  • 22