如何从表单中选择集合中的实体? Spring MVC和Thymeleaf

CompanySet 中有一些 User 实体,所有用户都存储在DB中 . 我想以HTML格式选择一些使用 multiple-select 的用户 . 使用Thymeleaf和Spring(MVC,Boot) .

我_752502已经尝试过@InitBinder,Spring Core Converter,但没有任何效果 . 问题: @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>

如何实现这种多选的正确方法是什么?

回答(1)

2 years ago

你可以使用这段代码

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

(在th:value中看起来是双{{}}) .

现在你需要一个这样的格式化程序:

@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());
}