now available

now available
Want fresh tech tips in your inbox?

Extending Rails Form Builders


Extending forms in Rails is simple and will greatly reduce the amount of code in your views. This example is taken right from the Agile Web Development book on Rails(2.1.*) with one minor tweak. I want to pass a label argument along with the field name so that I can display a more human friendly string to represent the form field.

# RAILS_ROOT/app/helpers/custom_tag_builder.rb
class CustomTagBuilder < ActionView::Helpers::FormBuilder

  def self.create_tagged_field(method_name)
    define_method(method_name) do |label, *args|
      label_name = args.first.blank? ? label : args.first[:label] # my change
          label_name.to_s.humanize, :for => "#{@object_name}_#{label}") +" 
"+ super) end end field_helpers.each do |name| create_tagged_field(name) end end

You can then use this in your views

form_for @your_model, :builder => CustomTagBuilder do |f|
  f.text_field :fullname
  f.text_field :email, :label => "Email (will not be published)"
My change tests for the presence of a label argument otherwise using the name of the form field/model attribute. In this case the fullname attribute will be outputted as "Fullname" while "Email (will not be published)" as the label for the email text field.

Tagged w/ #builders #custom tag builder #extending #forms #label #rails #template #text fieldruby on rails

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app