Search code examples
springspring-mvcthymeleaf

How to save relations based on checkboxes using Theyleaf and Spring MVC


I am using Spring Boot 1.5 with Thymeleaf 3.

Lets have many to many relation between entities Place and 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;

}

Now I want to list every category and allow user to select some categories. Selected categories should be added to Place.categories set (thus creating a relation)

How can I do that?

I have following form fragment:

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

Where I assumed that allServices is a result of serviceRepository.findAll() so simple list containing all services, and selectedServices would be a collection returned by ${place.services} (effectively, selected categories)

This displays list just fine, but how to bind selection to my place entity?


Solution

  • This is the correct answer which I have found out short after submitting a question. Works more than good.

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