Wordpress-style forms in Rails

Today I completed something I should have done half a year earlier. In the Z@PP admin CMS, I use Wordpress-style forms. These have lots of repeating table rows, and I had a lot of duplication in there. Today I cleaned everything right up and went from hundreds of lines of code to a couple dozen!

A Form Builder does exactly what it says on the box: it builds forms to be used in web pages. Here is the particular code I ended up with. I think it’s fairly clever.

class WordpressFormBuilder < 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

def th(field, options)
@template.content_tag :th, :scope => 'row', :valign => 'top' do
label(field, options.delete(:label))
end
end

def content(tag, options)
if description = options.delete(:description)
tag + @template.tag(:br) + @template.content_tag(:em, description)
else
tag
end
end

helpers.each do |name|
define_method(name) do |field, *args|
options = args.extract_options!

if options.delete(:builder) == :default
super
else
@template.content_tag :tr,
th(field, options) + @template.content_tag(:td, content(super, options)),
:class => 'form-field'
end
end
end
end

How it works

There are three pieces to this puzzle: tell a regular Rails form to use this builder, use the form’s elements and the final display on screen.

I decided against using this custom builder for all my forms. This means I must enable this builder explicitly:

form_for @user, :builder => WordpressFormBuilder do |form|
....
end

Then the easy part: form elements are unchanged.

form.text_field :login

And the end result is a nicely decorated form element, complete in a fully-formatted table row.

Nice.

  1. No comments yet.

  1. No trackbacks yet.