Search code examples
validationspring-mvcthymeleafspring-validator

How to select entities from collection in form? Spring MVC and Thymeleaf


Company has some User entities in Set, all users are stored in DB. I want to select some users using multiple-select in HTML form. Using Thymeleaf and Spring (MVC, Boot).

I'm totally lost in what I should use. I've tried @InitBinder, Spring Core Converter, but nothing worked. Problem: @Controller failes on bindingResult.hasErrors():

@Controller

@RequestMapping(value = { "/add" }, method = { RequestMethod.POST })
public String saveNew(@Validated @ModelAttribute("company") Company company, BindingResult bindingResult, Model model) {
    if (bindingResult.hasErrors())

Company bean

public class Company {
    private Set<User> users = new HashSet<User>();

Thymeleaf HTML form

<form th:object="${company}">
<select th:field="*{users}" multiple="multiple">
    <option th:each="user : ${allUsers}" th:value="${user.id}" th:text="${user.email}"></option>
</select>

What is the proper way how to implement this multiple-select?


Solution

  • you can use this code

    <form th:object="${company}">
    <select th:field="*{users}" multiple="multiple">
        <option th:each="user : ${allUsers}" th:value="${{user}}" th:text="${user.email}"></option>
    </select>
    

    (look double {{}} in th:value).

    Now you need a formatter like this:

    @Component
    public class UserFormatter implements Formatter<User> {
    
    @Autowired
    private UserService userService;
    
    @Override
    public Dia parse(String text, Locale locale) throws ParseException {
        return userService.findById(Long.valueOf(text));
    }
    
    @Override
    public String print(User object, Locale locale) {
        return String.valueOf(object.getId());
    }