Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple hidden field in non-model form

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?

like image 383
Chowlett Avatar asked Dec 30 '22 02:12

Chowlett


1 Answers

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.

like image 153
Jimmy Avatar answered Jan 10 '23 18:01

Jimmy