OOPs Way of Handling Checkboxes using Thymeleaf

1. Introduction

In this tutorial, we will learn how to display/submit checkboxes in Thymeleaf by following Object Oriented Programming approach. We will create an input form and use a model object to submit form data to a Spring Controller.

2. Prepare Model Attribute

Let’s create a new entity that will hold the data required by a single radio box.

public class Month {

    private String name;
    private Boolean checked;

    // setters and getters

}

Next, we need to prepare a Model class that will contain a list of Month.

public class MonthGroup {

    private List<Month> months = new ArrayList<>();

    // setters and getters

}

Finally, we need to add MonthGroup object to Spring Model View.

modelAndView.addObject("monthGroup", new MonthGroup());

3. Prepare HTML Input Form

Let’s create a new input form with MonthGroup model object.The input form will display the list of the month and contains unique names per radio button.

<form th:object
="${monthGroup}" th:action="@{/checkbox-submit}" method="post">
  <div th:each="month, stat: ${monthGroup.months}">
    <input type="checkbox" th:field="*{months[__${stat.index}__].checked}" th:text="${month.name}">
  </div>
  <input type="submit" value="Submit">
</form>

Now we are done with all steps, and now we can deploy and run the application.

The input form will send a Boolean state true with every checked checkbox whenever a user submits the form. Also if any month has property checked true, it’s Thymeleaf that shows that checkbox state checked. You can try by putting Boolean state true in some of the month objects under model object.

4. Conclusion

In this tutorial, we have learned how to handle an HTML input form with checkboxes using Thymeleaf by following OOPs approach.

The complete source can be found over on GitHub.

Leave a Reply

Your email address will not be published. Required fields are marked *