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?

user938363
  • 9,990
  • 38
  • 137
  • 303

3 Answers3

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"

Thaha kp
  • 3,689
  • 1
  • 26
  • 25
  • 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. – user938363 Jul 29 '13 at 10:32
  • I am using this code and working. Please see the log while submitting the form whether params are sending or not. – Thaha kp Jul 29 '13 at 10:42
  • 17
    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 %>` – dax Aug 18 '13 at 12:34
  • 3
    actually i got it working with a hidden_field_tag instead, +1 though, thanks! – dax Aug 18 '13 at 12:55
  • what if you want to pass more than 1 param? – daslicious Jan 09 '18 at 21:46
  • This worked for me `redirect_to users_url(1, params: {a: :b}, subdomain: 'bob')` – Liz Oct 12 '19 at 23:28
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]
emery
  • 8,603
  • 10
  • 44
  • 51
17

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.

chrislopresto
  • 1,598
  • 1
  • 10
  • 22