Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 255
Xdg Avatar asked Oct 24 '25 21:10

Xdg


1 Answers

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());
}
like image 85
user3528134 Avatar answered Oct 26 '25 22:10

user3528134