A FormBuilder object is associated with a particular model object and allows you to generate fields associated with the model object. The FormBuilder object is yielded when using form_for or fields_for. For example:

<%= form_for @person do |person_form| %>
  Name: <%= person_form.text_field :name %>
  Admin: <%= person_form.check_box :admin %>
<% end %>

In the above block, a FormBuilder object is yielded as the person_form variable. This allows you to generate the text_field and check_box fields by specifying their eponymous methods, which modify the underlying template and associates the @person model object with the form.

The FormBuilder object can be thought of as serving as a proxy for the methods in the FormHelper module. This class, however, allows you to call methods with the model object you are building the form for.

You can create your own custom FormBuilder templates by subclassing this class. For example:

class MyFormBuilder < ActionView::Helpers::FormBuilder
  def div_radio_button(method, tag_value, options = {})
    @template.content_tag(:div,
      @template.radio_button(
        @object_name, method, tag_value, objectify_options(options)
      )
    )
  end
end

The above code creates a new method div_radio_button which wraps a div around the new radio button. Note that when options are passed in, you must call objectify_options in order for the model object to get correctly passed to the method. If objectify_options is not called, then the newly created helper will not be linked back to the model.

The div_radio_button code from above can now be used as follows:

<%= form_for @person, :builder => MyFormBuilder do |f| %>
  I am a child: <%= f.div_radio_button(:admin, "child") %>
  I am an adult: <%= f.div_radio_button(:admin, "adult") %>
<% end -%>

The standard set of helper methods for form building are located in the field_helpers class attribute.

Show files where this class is defined (2 files)
Register or log in to add new notes.
October 30, 2009
7 thanks

How FormBuilders work

What, you were expecting documentation? :)

An excellent survey of how FormBuilders work is here:

http://code.alexreisner.com/articles/form-builders-in-rails.html

November 22, 2013
0 thanks