Thymeleaf 预选 Select2 选项

Thymeleaf Preselected Select2 Options

我正在尝试使用 select2 呈现具有多个 select 列表的编辑页面。根据 select2 文档,只需设置一个选项 selected="selected" 就可以了,但我使用的是 Java/Spring 和 Thymeleaf 模板,所以有点棘手。

<select id="programs" name="programs.id" style="min-width: 200px;" multiple="multiple">
    <option
            th:each="programs : ${programs}"
            th:value="${programs.id}"
            th:text="'['+${programs.category.name}+'] '+${programs.name}"
            th:selected="${#lists.contains(personProg,programs.id)}">
    </option>
</select>

programs.id 是程序的 ID,personProg 是与个人 ID 相关联的程序列表,因此,在列表中预先 select。

这可以正常编译和加载,但没有任何选项 selected。没有 html 或任何东西,我看了几个注意到 #lists.contains() 方法的问题。我看到它不适用于 th:field 属性,但我也没有。

Java供参考:

@RequestMapping(value="edit", method=RequestMethod.GET)
public String Edit(Model model, @RequestParam(value="userID") long id) {
    Person person = repo.findById(id);
    model.addAttribute("person", person);
    model.addAttribute("users", repo.findByOrderByLastnameAsc());
    model.addAttribute("programs", progRepo.findByOrderByIdAsc());
    model.addAttribute("personProg", personProgRepo.findByPersonid(person.getID()));
    for (PersonPrograms x : personProgRepo.findByPersonid(person.getID())) {
        System.out.println(x.getProgramid());
    }
    return "edit";
}

java 控制台中的输出:

69
1
2
3
66
6
37
59
58

我做错了什么?

发送的模型属性是一个 personProg 列表,而不是您想要的 ID 列表。制作一个列表,并发送 ID 列表而不是对象列表。

List<Integer> programIdList = new ArrayList<Integer>();
for (PersonPrograms x : personProgRepo.findByPersonid(person.getID())) {
   programIdList.add(x.getProgramid());
}
model.addAttribute("personProg", programIdList.toString());