Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf multiple submit button in one form

I have a fragment of HTML page with one form and 2 button:

<form action="#" data-th-action="@{/action/edit}" data-th-object="${model}" method="post">     <button type="submit" name="action" value="save">save</button>     <button type="submit" name="action" value="cancel">cancel</button> </form> 

And the controller:

@RequestMapping(value="/edit", method=RequestMethod.POST) public ModelAndView edit(@ModelAttribute SomeModel model,          @RequestParam(value="action", required=true) String action) {      if (action.equals("save")) {         // do something here          }      if (action.equals("cancel")) {        // do another thing     }     return modelAndView; } 

This work good, but if I have more button, I must add more if statement to check the action string. Is there another way that I can create one action for each button in the form?

like image 437
Liem Do Avatar asked Jul 14 '15 08:07

Liem Do


People also ask

How do I apply multiple submit buttons in one form?

Let's learn the steps of performing multiple actions with multiple buttons in a single HTML form: Create a form with method 'post' and set the value of the action attribute to a default URL where you want to send the form data. Create the input fields inside the as per your concern. Create a button with type submit.

Can a form have 2 submit buttons?

yes, multiple submit buttons can include in the html form. One simple example is given below.

How do you pass two objects to a form using Thymeleaf?

The only way I found is to build an other object containing those two objects, and pass it. That works well, but I can't create that kind of object, it's nonsense (even if it works). Of course, the objects aren't as simple as Foo and Bar here, otherwise I would have merge those two.


Video Answer


1 Answers

You can create separate methods with different @RequestMappings using the params variable.

@RequestMapping(value="/edit", method=RequestMethod.POST, params="action=save") public ModelAndView save() {}   @RequestMapping(value="/edit", method=RequestMethod.POST, params="action=cancel") public ModelAndView cancel() {} 
like image 158
Kayaman Avatar answered Sep 24 '22 11:09

Kayaman