Advanced Rails Studio: Custom Form Builder 7
Custom Form Builder
Use a custom form builder to clean up your html.erb files.
lib/label_form_builder.rb
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 +'<br/>' + super) #wrap with a paragraph
end
end
endThen you can remove all the <p> and label tags from you form.
app/views/users/edit.html.erb
<h1>Editing user</h1>
<% 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<% form_for(@user, :builder => LabelFormBuilder) do |f| %><% form_for(@user) do |f| %>Now the same form with no custom builder was looking like this before.
<h1>Editing user</h1>
<% form_for(@user) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<p>
<%= f.label :address %><br />
<%= f.text_field :address %>
</p>
<p>
<%= f.label :comment %><br />
<%= f.text_area :comment %>
</p>
<p>
<%= f.label :check %><br />
<%= f.check_box :check %>
</p>
<p>
<%= f.submit "Update" %>
</p>
<% end %>
<%= link_to 'Show', @user %> |
<%= link_to 'Back', users_path %>
Thanks!! :)
Thanks a lot for sharing!
To avoid HTML validation errors you should write in the LabelFormBuilder class:
label = label(field, options.delete(:label), :class => options.delete(:label_class))Beware of the “options.delete”. Otherwise the inputs will have non-valid attributes “label” and “label_class”.
Now you can write:
<%= f.text_field :name, :label => 'Surname' %>Where is the best place to put the customer form builder class?
Where is the best place to put the customer form builder class?
simply put following line into your environment.rb file:
config.load_paths += %W( #{RAILS_ROOT}/app/builders )
and your builder under app/builders
I think a better place to put it is the helpers directory and you won’t need to load the path.
You can replace
options = args.last.is_a?(Hash) ? args.pop : {}with predefined Rails method
options = args.extract_options!