开发者

Simple hidden field in non-model form

开发者 https://www.devze.com 2022-12-19 06:26 出处:网络
What\'s the simplest way in Ruby-on-Rails to create several simple hidden fields with known values and the same name in a number of non-model forms (form_remote_tag in my case, but I\'m guessing that

What's the simplest way in Ruby-on-Rails to create several simple hidden fields with known values and the same name in a number of non-model forms (form_remote_tag in my case, but I'm guessing that isn't relevant)?

By "simple hidden field", I mean one where the name is just a single string (field_name) rather than part of an array (field_name[]), so that the value can be read simply from the params hash as params[:field_name] rather than params[:field_name][0].

I have found that

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

produces an acceptable element (<input id="field_name_0" name="field_name" type="hidden" value="foo" />), but if I omit the :name开发者_开发问答 parameter then the rendered field has the name field_name[0]. Omitting the 0 obviously causes really odd behaviour.

<%= hidden_field_tag :field_name, "foo" %> produces an acceptable element if there's only one such form, but generates HTML warnings (duplicate IDs) if there are more than one.

Is there a way to do this (barring defining a helper) in fewer arguments?


I would use hidden_field_tag and set the ID 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_value can be anything at all. If these forms have some sort of parent record that they refer to, it could be the ID of the parent. I assume that's why you have multiple similar forms on the same page in the first place.


You can simple pass the ID as an option. The method (form_tag_helper.rb) is defined as:

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

So writing:

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

Produces:

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


Try hidden_field_tag:

<%= hidden_field_tag :field_name, "foo" %>
0

精彩评论

暂无评论...
验证码 换一张
取 消