How To Use Multiple Submit Buttons on a Form with Rails
Sep 10, 2006One problem that commonly comes up in designing web application UI’s is wanting to allow your users do more than just one action with a form.
I’m going to use Simplist as an example, as it allows you to preview changes to a blog post before saving and making the changes permanent. This is implemented through two submit buttons on the same form that perform different actions.
Creating the Form
You create the form just like you would any other, the exception being how to you create the submit buttons.
<% start_form_tag :action => "submit_form" %> ... <%= submit_tag 'Preview', :name => "submit" %> <%= submit_tag 'Save', :name => "submit" %> <% end_form_tag %>
You can see that we give the submit tags the same name, but different text values for the button labels. These two pieces of information allow us to determine which submit button our user clicked when they submitted the form.
Handling the Form Submission
In the corresponding action in our controller we use a conditional statement to handle the form submission.
def submit_form
case params[:submit]
when "Preview"
redirect_to :action => "preview"
return
when "Save"
redirect_to :action => "save"
return
end
end
As you can see since our submit buttons were given the same name attribute we only need to see what value is stored in the params hash upon form submission to determine which button our user clicked. Once we know that we can execute the necessary code to handle each button click.
This method works for any number of submit buttons, and merely depends on adding conditional logic for each button.