我正在使用Spring Boot 1.5和Thymeleaf 3。
让实体Place
和Category
public class Category extends AbstractEntity {
@Column
private String name;
@ManyToMany(mappedBy = "categories")
private Set<Place> places;
}
public class Place extends AbstractEntity {
@ManyToMany
@JoinTable(joinColumns = @JoinColumn(name = "place_id"),inverseJoinColumns=@JoinColumn(name="category_id"))
private Set<Category> categories;
}
现在我想列出每个类别,并允许用户选择一些类别。应将选定的类别添加到Place.categories
集(从而创建关系)
我该怎么做?
我有以下form
片段:
<div th:fragment="services(selectedServices,allServices)">
<fieldset>
<legend>Select services</legend>
<div class="checkbox" th:object="${selectedServices}" th:each="service : ${allServices}">
<label> <input th:value="${service.id}" type="checkbox" /> <span th:text="${service.name}" th:remove="tag"> </span>
</label>
</div>
</fieldset>
</div>
我认为allServices
是包含所有服务的serviceRepository.findAll()
如此简单列表的结果,而selectedServices
将是${place.services}
返回的集合(实际上,选定的类别) )
这显示列表很好,但是如何将选择绑定到我的place
实体?
答案 0 :(得分:1)
尝试这样做:
<div class="checkbox" th:each="category : ${allCategories}">
<input type="checkbox" th:field="*{categories}" th:value="${category.name}" class="checkbox"/>
</div>
在表单中。
答案 1 :(得分:0)
这是我在提交问题后发现的正确答案。效果不错。
<div th:fragment="categories(place,allCategories)">
<fieldset th:object="${place}" th:classappend="${#fields.hasErrors('categories')} ? 'has-error' : _ ">
<legend>Select categories</legend>
<div class="checkbox" th:object="${place}" th:each="category : ${allCategories}">
<label> <input th:value="${category.id}" th:field="*{categories}" type="checkbox" /> <span th:text="${category.name}" th:remove="tag"> </span>
</label>
</div>
<span class="help-block" th:each="msg : ${#fields.errors('categories')}" th:text="${msg}">Some error message for this field</span>
</fieldset>
</div>