Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create multiple submit buttons for the same form in Rails?

I need to have multiple submit buttons.

I have a form which creates an instance of Contact_Call.

One button creates it as normal.

The other button creates it but needs to have a different :attribute value from the default, and it also needs to set the attribute on a different, but related model used in the controller.

How do I do that? I can't change the route, so is there a way to send a different variable that gets picked up by [:params]?

And if I do then, what do I do in the controller, set up a case statement?

like image 239
Satchel Avatar asked Jun 12 '10 01:06

Satchel


People also ask

Can I have two or more Submit buttons in the same form?

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

How many submit buttons can be applied?

Two submit buttons in one form.

Can you have multiple submit buttons in a form MVC?

One Form can do a POST submission to one Action method in Controller and hence in order to use multiple Submit buttons inside one single Form, a Switch case has to be implemented inside the Action method.

Does every form need a submit button?

If you don't have any submit button it is acceptable after all it is an element of form tag and if it is not required you may not add it with in form . This will not broke any web standard.


2 Answers

You can create multiple submit buttons and provide a different value to each:

<% form_for(something) do |f| %>     ..     <%= f.submit 'A' %>     <%= f.submit 'B' %>     .. <% end %> 

This will output:

<input type="submit" value="A" id=".." name="commit" /> <input type="submit" value="B" id=".." name="commit" /> 

Inside your controller, the submitted button's value will be identified by the parameter commit. Check the value to do the required processing:

def <controller action>     if params[:commit] == 'A'         # A was pressed      elsif params[:commit] == 'B'         # B was pressed     end end 

However, remember that this tightly couples your view to the controller which may not be very desirable.

like image 128
Anurag Avatar answered Sep 18 '22 08:09

Anurag


There is also another approach, using the formaction attribute on the submit button:

<% form_for(something) do |f| %>     ...     <%= f.submit "Create" %>     <%= f.submit "Special Action", formaction: special_action_path %> <% end %> 

The code stays clean, as the standard create button doesn't need any change, you only insert a routing path for the special button:

formaction:
The URI of a program that processes the information submitted by the input element, if it is a submit button or image. If specified, it overrides the action attribute of the element's form owner. Source: MDN

like image 31
patpir Avatar answered Sep 21 '22 08:09

patpir