mercredi 18 novembre 2020

Setting checkbox checked values in th:each in Thymeleaf

I've got a Movie entity and a Genres entity class, with Many to Many mapping. Users should be able to add new movies and edit their existing movies, including the genres. Here is how the form should work:

  1. Controller gets a list of all Genres from a database to create a checkbox for each Genre using th:each
  2. If the movie being edited already has Genres applied to it, then those checkboxes will become checked when the form is loaded
  3. When the user submits the form, the list of selected checkboxes is also submitted so they can be checked to save/delete Genres from the Movie as applicable.

The problem I'm having is when using th:field to bind to the Genre, as th:checked cannot be applied to an input with a th:field already applied to it. Here's what I've tried so far:

  1. Using th:field on each checkbox input, I can submit the form and retrieve all the checked values. The problem is I cannot select whether the checkbox is checked by default.
  2. I created a class that contains a Genre object and a boolean value (which checks if the movie has a genre prior to loading the form), and use this to generate my checkboxes. If I bind th:field to the boolean value only, then the checkboxes are checked, but when submitting the form I lose the Genre data and only get the boolean data.
  3. Tried losing th:field completely and using th:name, th:value and th:checked instead. Check marks are added but all data is lost on form submission (list == null)

Here is the current code that checks checkboxes but submits a null list:

    public class GenreChoice {
        private Genre genre;
        private boolean selected;
        
        //getters/setters
        
    }

HTML:

    <div class="form-check form-check-inline" 
        th:each="genreChoice, iter: *{genreChoices}">
        <input class="form-check-input" 
            type="checkbox" 
            th:id="${genreChoice.genre.name}" 
            th:name="${genreChoice.genre.name}"
            th:value="${genreChoice}"
            th:checked="${genreChoice.selected}" />
        <label class="form-check-label" th:for="${genreChoice.genre.name}" th:text="${' ' + genreChoice.genre.name}"></label>
    </div>



Aucun commentaire:

Enregistrer un commentaire