onrails.org home

Advanced Rails Studio: Custom Form Builder

Custom Form Builder

Use a custom form builder to clean up your html.erb files.

class LabelFormBuilder < ActionView::Helpers::FormBuilder
helpers = field_helpers +
%w{date_select datetime_select time_select} +
%w{collection_select select country_select time_zone_select} -
%w{hidden_field label fields_for} # Don’t decorate these

helpers.each do |name| define_method(name) do |field, *args| options = args.last.is_a?(Hash) ? args.pop : {} label = label(field, options[:label], :class => options[:label_clas]) @template.content_tag(:p, label +’
’ + super) #wrap with a paragraph end end

end

Then you can remove all the <p> and label tags from you form.

Editing user

<% form_for(@user, :builder => LabelFormBuilder) do |f| >
<
= f.error_messages >
<
= f.text_field :name >
<
= f.text_field :address >
<
= f.text_area :comment >
<
= f.check_box :check >
<
= f.submit “Update” >
<
end %>

<%= link_to ‘Show’, @user > |
<
= link_to ‘Back’, users_path %>

Add this to your application initializer to have all form use this form builder

ActionView::Base.default_form_builder = LabelFormBuilder

Then you can replace

<% form_for(@user, :builder => LabelFormBuilder) do |f| %>

with

<% form_for(@user) do |f| %>

Now the same form with no custom builder was looking like this before.

Editing user

<% form_for(@user) do |f| >
<
= f.error_messages %>

<%= f.label :name %>
<%= f.text_field :name %>

<%= f.label :address %>
<%= f.text_field :address %>

<%= f.label :comment %>
<%= f.text_area :comment %>

<%= f.label :check %>
<%= f.check_box :check %>

<%= f.submit “Update” %>

<% end %>

<%= link_to ‘Show’, @user > |
<
= link_to ‘Back’, users_path %>

Fork me on GitHub