Read more

Add a prefix to form field IDs

Arne Hartherz
March 03, 2011Software engineer at makandra GmbH

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

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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/:

Posted by Arne Hartherz to makandra dev (2011-03-03 16:06)