如何使用Theyleaf和Sping MVC基于复选框保存关系

时间:2017-09-07 16:03:18

标签: spring-mvc thymeleaf

我正在使用Spring Boot 1.5和Thymeleaf 3。

让实体PlaceCategory

之间存在多对多关系
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实体?

2 个答案:

答案 0 :(得分:1)

尝试这样做:

<div class="checkbox" th:each="category : ${allCategories}"> 
    <input type="checkbox" th:field="*{categories}" th:value="${category.name}" class="checkbox"/>
</div>

在表单中。

请同时查看此答案:https://stackoverflow.com/a/45845091/4491130

答案 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>