dimanche 21 octobre 2018

Passing checkbox values from form to Controller in Thymeleaf

my problem is that I cannot find anything regarding how to pass checkbox values ( checked / notchecked ) from a form to my @Controller. I use Thymeleaf for my frontend.

Here is my code:

<form action="#" th:action="@{/passwordaenderung}" th:object="${password}" method="post">
    <table border="1" style="width:50%">
        <thead>
            <tr>
                <th> Benutzername </th>
                <th> Passwort </th>
            </tr>
        </thead>
        <tbody>
        <tr th:if="${users.empty}">
                <td colspan="2"> No Users available</td>
            </tr>
            <tr th:each="user : ${users}">
                <td><input type="text" th:value="${user.benutzername}" name="username" id="username"></td>
                <td><input type="text" id="password" name="password" required />
                <td><input type="checkbox" th:field="*{multiCheckboxSelectedValues}" />
            </tr>
        </tbody>
    </table>
    <input type="submit" value="Submit">
</form>

And here is my controller:

   @PostMapping
    public String updateOldPassword(@Valid @ModelAttribute("password") PasswordChange userAndpassword,
            BindingResult result, ModelMap model) {
    if (result.hasErrors()) {
        return "error";
    }

    String username = userAndpassword.getUsername();
    String password = userAndpassword.getPassword();

    String newPassword = passwordEncoder.encode(password);

    passwordRepo.updatePassword(username, newPassword);
    return "redirect:/";
}

I want accomplish, if it is possible, to put all my fields into a list so that I have username, password, and the checkbox in a list.




Aucun commentaire:

Enregistrer un commentaire