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?
yes, multiple submit buttons can include in the html form. One simple example is given below.
Two submit buttons in one form.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With