Skip to content
Advertisement

Bind list or array to form in Thymleaf

On my website I have a few checkboxes each of them contains id in value attribute. After submitting form I’d like to have a list containing ids of checked checkboxes to be passed to the controller. That’s how I want to make new page comparing n products.

Controller can accept List<Long> or long[]. That’s what I have for now:

HTML:

<form th:action="@{/comparison}" th:object="${productsComparison}" target="_blank" method="post">
<table>
  <tr data-th-each="item, iter : ${items.item}">
    <td>
      <input type="checkbox" th:name="|productsComparison.ids[${iter.index}]|" th:value="${item.id}"/>
    </td>
  </tr>
</table>

I’ve added to my controller List<Long> wrapped in ProductComparison with appropriate getters and setters. After submitting form list is always null.

Controller:

@RequestMapping("/productsPage")
public String showProducts(Model model) {
    ProductsComparison productsComparison = new ProductsComparison();
    model.addAttribute("productsComparison", productsComparison);
}

@RequestMapping("/comparison")
public String compareProducts(@ModelAttribute ProductsComparison productsComparison) {
    System.out.println("List: " + productComparison.getIds());
    // Always shows null
    return "comparison";
}
public class ProductsComparison {
    private List<Long> ids;
    // Getters & setters
}

Advertisement

Answer

I’ve finally found solution. Instead of th:name I had to use th:field.

th:field="*{ids[__${iter.index}__]}"

Because it’s field I didn’t have to specify object productsComparison before ids. ids field is List<String>.

To be honest I have no idea what underscores do, I will be glad if someone could explain.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement