24

I would like to use the form_for helper multiple times for the same model in the same page. But the input fields use the same ID attribute (in the HTML), so clicking on the label of a field in another form will select the same input in the first form.

Is there a solution besides settings all attributes manually via :for => "title_#{item.id}" and :id => "title_#{item.id}"?

Using Rails 3.0.9

3 Answers 3

33

You can use :namespace => 'some_unique_prefix' option. In contrast to :index, this will not change the value used in the name attribute.

It's also possible to use an array, e.g. when you have nested forms or different forms that happen to have some fields in common: :namespace => [@product.id, tag.id] or :namespace => [:product, @product.id]

Sign up to request clarification or add additional context in comments.

2 Comments

It’s worth pointing out that this only works in Rails 3.2 and up.
Maybe this is not obviously, but :namespace is to be used in form_for. For example: form_for :user, :url => user_session_path, :html => { :class => 'form-inline' }, :namespace => 'quick' do |f|
11

I found the answer myself, one can pass a :index option to form_for. That string will be used in the id and for attributes:

<%= form_for @person, :index => @person.id do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  <%= f.submit %>
<% end %>

will parse

<form accept-charset="UTF-8" action="/person/11" class="edit_person" id="edit_person_11" method="post">
  <!-- Hidden div for csrf removed -->
<label for="person_11_name">Name</label> 
<input id="person_11_name" name="person[11][name]" size="30" type="text" /> 
<input name="commit" type="submit" value="Update Person" /> 
</form>

Notice it'll change the name of the inputs as well.

Comments

-6

I believe you can add this param:

:html => { :id => 'id_i_want' }

1 Comment

That will change the id of the form itself, not the inputs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.