rails simple_form - hidden field - create?

Ruby on-RailsRuby on-Rails-3Form ForHidden FieldSimple Form

Ruby on-Rails Problem Overview


How can you have a hidden field with simple form?

The following code:

= simple_form_for @movie do |f|
  = f.hidden :title, "some value"
  = f.button :submit

results in this error:

undefined method `hidden' for #SimpleForm::FormBuilder:0x000001042b7cd0

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

try this

= f.input :title, :as => :hidden, :input_html => { :value => "some value" }

Solution 2 - Ruby on-Rails

Shortest Yet !!!

=f.hidden_field :title, :value => "some value"

Shorter, DRYer and perhaps more obvious.

Of course with ruby 1.9 and the new hash format we can go 3 characters shorter with...

=f.hidden_field :title, value: "some value"

Solution 3 - Ruby on-Rails

Correct way (if you are not trying to reset the value of the hidden_field input) is:

f.hidden_field :method, :value => value_of_the_hidden_field_as_it_comes_through_in_your_form

Where :method is the method that when called on the object results in the value you want

So following the example above:

= simple_form_for @movie do |f|
  = f.hidden :title, "some value"
  = f.button :submit

The code used in the example will reset the value (:title) of @movie being passed by the form. If you need to access the value (:title) of a movie, instead of resetting it, do this:

= simple_form_for @movie do |f|
  = f.hidden :title, :value => params[:movie][:title]
  = f.button :submit

Again only use my answer is you do not want to reset the value submitted by the user.

I hope this makes sense.

Solution 4 - Ruby on-Rails

= f.input_field :title, as: :hidden, value: "some value"

Is also an option. Note, however, that it skips any wrapper defined for your form builder.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLinus OleanderView Question on Stackoverflow
Solution 1 - Ruby on-Railsfl00rView Answer on Stackoverflow
Solution 2 - Ruby on-RailsMichael DurrantView Answer on Stackoverflow
Solution 3 - Ruby on-RailsUzzarView Answer on Stackoverflow
Solution 4 - Ruby on-RailsFuad SaudView Answer on Stackoverflow