Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Multi-submit buttons in one Form

Say I have an Article model, and in the article 'new' view I have two buttons, "Publish" and "Save Draft".

My question is how can I know which button is clicked in the controller.

I already have a solution but I think there must be a better way. What I currently used in the view is:

<div class="actions">   <%= f.submit "Publish" %>   <%= f.submit "Save Draft", :name => "commit" %> </div> 

So in the controller, I can use the params[:commit] string to handle that action.

def create   @article = Article.new(params[:article])   if params[:commit] == "Publish"     @article.status = 'publish'     // detail omitted   end    @article.save end 

But I think using the view related string is not good. Could you tell me another way to accomplish this?

UPDATE: Since these buttons are in the same form, they're all going to the 'create' action, and that's OK for me. What I want is to handle that within the create action, such as give the Article model a 'status' column and holds 'public' or 'draft'.

like image 815
kinopyo Avatar asked Jul 26 '10 05:07

kinopyo


People also ask

Can you have multiple submit buttons in a form?

yes, multiple submit buttons can include in the html form.

Can I have two submit buttons in a form react?

Basically just add the buttons to the DOM inside my form and collect the values from the event that I have access to inside of the submit handler. Why not use onClick for each button? You can have a separate handler for each, or pass an argument to a shared handler.


1 Answers

This was covered in Railscast episode 38. Using the params hash to detect which button was clicked is the correct approach:

View:

<%= submit_tag 'Create' %> <%= submit_tag 'Create and Add Another', name: 'create_and_add' %> 

Controller:

if params[:create_and_add]   # Redirect to new form, for example.  else   # Redirect to show the newly created record, for example. end 
like image 199
John Topley Avatar answered Sep 21 '22 18:09

John Topley