Add a prefix to form field IDs

Updated . Posted . Visible to the public.

If you use a form (or form fields) multiple times inside one view, Rails will generate the same id attributes for fields again.

This card presents you with a way to call something like

- form_for @user, :prefix => 'overlay' do |form|
  = form.text_field :email

and get this as HTML:

<input name="user[email]" id="overlay_user_email" (...) />

You can also put a :prefix into a field's options. Note how only the id but not the name changes as we would not want to pass an overlay_user[email] param to the controller. Setting :id explicitly will not be affected by the prefix.

First, have your FormBuilder keep the :prefix inside the @default_options which is passed to field helper methods. If you use your own FormBuilder class, it would look like this:

class FunkyFormBuilder < ActionView::Helpers::FormBuilder
  def initialize(*args)
    super.tap do
      @default_options = @options ? @options.slice(:index, :prefix) : {}
    end
  end
end

To have the prefix applied to all form field ids, put this into config/initializers/:

Arne Hartherz
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2011-03-03 15:06)