Kabindra Shrestha
Kabindra Shrestha

Reputation: 333

Getting value of list of checkboxes using thymeleaf, spring boot

Here, i have a form which have list of user with checkboxes. I need to get boolean values as well as user ids of respective checkboxes to know the boolean value whether true or false for each user to insert values as per user in the database. For Example:

enter image description here

Let's say we have three users of id 1,2,3 then i need the checkbox checked value like 1,0,1 for respective user. So, as to insert boolean value for the user if checked or not.

<-- main.html -->

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en" th:include="fragments/header :: header">
</head>
<body>
    <div lang="en" th:include="fragments/navigation :: navigation"></div>

    <div class="container" id="attendanceDiv">
        <div class="alert alert-success" role="alert"
            th:if="${error} == 'false'" th:text="${message}"></div>

        <div class="alert alert-danger" role="alert"
            th:if="${error} == 'true'" th:text="${message}"></div>

        <h3>Add</h3>
        <hr></hr>
        <form id="attendanceform" class="col-xs-12 col-sm-4" role="form"
            th:action="@{/attendance/createall}" method="post">
            <div class="checkbox" th:each="users : ${users}">
                <label> 
                    <input type="checkbox" id="present" name="present"
                    th:text="${users.firstname} + ' ' + ${users.lastname}"></input> 
                    <input type="hidden" id="user" name="user" th:value="${users.id}" />
                </label>
            </div>
            <div>
                <p>
                    <button type="submit" class="btn btn-default">Save</button>
                </p>
            </div>
        </form>
    </div>

    <div lang="en" th:include="fragments/footer :: footer"></div>
</body>
</html>

Please help me i don't know how to get input data for multiple checkboxes and i am using spring boot, spring data jpa with thymeleaf.

Upvotes: 2

Views: 8438

Answers (1)

Sigrist
Sigrist

Reputation: 1471

First at all, your checkbox must have a value field. In the java method to process this form, should be like:

@RequestMapping("/attendance/createall")
public ResponseEntity<String> foo(@RequestParam("present") List<String> values) {

    //.....
}

Upvotes: 2

Related Questions