Home > database >  When thymeleaf form is submitted then handler in controller was not called
When thymeleaf form is submitted then handler in controller was not called

Time:08-29

As a model for my form I'm using

...
@NoArgsConstructor
@AllArgsConstructor
@Data
public class FormDto {
    private UUID id;
    private Set<UUID> items;
}

then I have this checkbox_form:

<form action="#" th:action="@{/roles/checkboxForm}" th:object="${dto}" method="post">

    <fieldset>
        <input type="hidden" th:field="*{roleId}" th:value="*{roleId}" />

        <div  th:each="user : ${users}">
            <div >
                <input type="checkbox" th:field="*{items}" th:value="${user.id}" th:id="${user.id}"/>
                <label th:for="${user.id}" th:text="${user.lastName}"></label>
            </div>
        </div>

        <hr/>

        <button type="submit" name="action" value="save">add</button>
        <button type="submit" name="action" value="cancel">cancel</button>

    </fieldset>
</form>

and in Controller class I have two methods - GET and POST:

    @GetMapping(value = "/list")
    public String getCheckboxForm(Model model) {

        var users = userService.getAllUsers();

        model.addAttribute("dto", new RoleAddUsersDto());
        model.addAttribute("users", users);

        return "checkbox_form";
    }

    @PostMapping(value = "/checkboxForm")
    public String handleCheckboxFormSubmit(@ModelAttribute("dto") RoleAddUsersDto dto,
                                           BindingResult bindingResult,
                                           Model model) {
        return "home";
    }

Here are raw form data from POST call:

id=0186d463-8661-4c25-bd5b-4fd75d3297ff&_items=on&_items=on&items=01d71d78-6697-41c1-a2ab-2c04d4dad576&_items=on&items=08d71d78-6697-41c1-a2ab-2c04d4dad576&_items=on&_items=on&_items=on&_items=on&_items=on&_items=on&_items=on&_items=on&_items=on&_items=on&_items=on&_items=on&_items=on&_items=on&_items=on&_items=on&_items=on&_items=on&action=submit

but after form submit it never goes to handleCheckboxFormSubmit in controller. I can't find what's wrong.

CodePudding user response:

Are you sure it never goes to handleCheckboxFormSubmit? If you submit the form and it takes you to home, then handleCheckboxFormSubmit is working as it's supposed to.

You're not doing anything in it so you wouldn't really know if it was called.

In handleCheckboxFormSubmit, add System.out.println("hello world"). Reload and hit submit the form again, and check your console output. You should see hello world there.

Another issue might be the multiple submit buttons. Read on th:formaction and checkout this answer by Parth Sarkheliya: https://stackoverflow.com/a/61013622/18902234

  • Related