Simple hidden field in non-model form

The easiest way in Ruby-on-Rails to create some simple hidden fields with known values โ€‹โ€‹and the same name in several non-model forms (form_remote_tag in my case, but I assume it doesn't matter)?

By โ€œplain hidden fieldโ€ I mean one where the name is only one string ( field_name), and not part of the array ( field_name[]), so the value can simply be read from the params hash as params[:field_name], rather than params[:field_name][0].

I found that

<% form_remote_tag :url => {:action => "do_act"} do %>
  <%= hidden_field :field_name, 0, :name => "field_name", :value => "foo" %>
  <%= submit_tag "Submit" %>
<% end %>

creates an acceptable element ( <input id="field_name_0" name="field_name" type="hidden" value="foo" />), but if I omit the parameter :name, then the displayed field has a name field_name[0]. Lowering 0obviously causes a really strange behavior.

<%= hidden_field_tag :field_name, "foo" %> creates an acceptable element if there is only one such form, but generates HTML warnings (duplicate identifiers) if there are more.

Is there a way to do this (prohibiting helper definitions) in fewer arguments?

+3
source share
3 answers

I would use hidden_field_tagand set the identifier manually based on some value that is different for each form. Like this:

<%= hidden_field_tag :field_name, 'value', :id => 'field_name_' + unique_value %>

Where unique_valuecould there be anything at all. If these forms have some kind of parent record to which they refer, this may be the identifier of the parent. I assume that in the first place you have several similar forms on one page.

+6
source

. (form_tag_helper.rb) :

def hidden_field_tag(name, value = nil, options = {})
  text_field_tag(name, value, options.stringify_keys.update("type" => "hidden"))
end

, :

<%= hidden_field_tag :field_name, "foo", :id => "hidden_field_1" %>
<%= hidden_field_tag :field_name, "bar", :id => "hidden_field_2" %>

:

<input id="hidden_field_1" name="field_name" type="hidden" value="foo" />
<input id="hidden_field_2" name="field_name" type="hidden" value="bar" />
+3

hidden_field_tag:

<%= hidden_field_tag :field_name, "foo" %>
+1
source

Source: https://habr.com/ru/post/1731840/


All Articles