29

In simple_form view, the submit button is like this:

<%= f.button :submit, 'Save' %>

We are trying to pass a params subaction when clicking the Save button. The params[:subaction] should have value of 'update' after clicking the button. Here is what we tried in view but it did not work:

<%= f.button :submit, 'Save', :subaction => 'update' %>

Is there a way to pass a value in params[:subaction] when clicking the Save button?

3 Answers 3

48

Use name and value option.

   <%= f.button  :submit , name: "subaction",value: "update"%>

In your controller you will get params[:subaction] with the value "update"

Sign up to request clarification or add additional context in comments.

6 Comments

Tried <%= f.button :submit, name: 'subaction', value: for_which, :class => BUTTONS_CLS['action'] %> and for_which is a string and the params[:subaction] is nil. It did not work.
I am using this code and working. Please see the log while submitting the form whether params are sending or not.
just tried this and it's working for what i need, but it's changing the submit button's text to the value of "value:" - is there a way to keep the name/value giving the controller the info it needs while still having a name of my choosing for the submit button? ie: button text should be "next student" but it's "2" <%= f.submit "Next student", :class => 'big_button round unselectable', name: "student_group_id", value: @student_group.id %>
actually i got it working with a hidden_field_tag instead, +1 though, thanks!
what if you want to pass more than 1 param?
|
25

as dax points out,

<%= hidden_field_tag(:subaction, 'update') %>
<%= f.button :submit, 'Save' %>

This will provide the string value 'update' to the routed controller action via the hidden field. It can then be retrieved by the controller with

params[:subaction]

1 Comment

the main thing, that you hidden_field_tag must be without f, which refers to model.
19

By specifying f.button :button, type: 'submit', we can use the name and value attributes as follows to submit using a single param. Notably, the value submitted (e.g., 'cake') may be different from the button text (e.g., 'The Best Cake').

_form.html.erb

<%= f.button :button, 'The Best Cake', type: 'submit', name: 'dessert_choice', value: 'cake' %>
<%= f.button :button, 'The Best Pie', type: 'submit', name: 'dessert_choice', value: 'pie' %>

Controller

def controller_action
  dessert_choice = params[:dessert_choice] # 'cake' or 'pie'
end

This approach avoids the need for hidden inputs as @dax mentioned in the comment above.

Tested on Simple Form 3.3.1 with Rails 4.2.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.