Help with custom FormBuilder

Joshua Muheim
2007-03-20T23:04:00Z

Hi all

I''m working on a custom FormBuilder that should be able to handle habtm
and has_many relationships with just one single method call, similar to
the existing text_field, text_area etc. methods.

My code in a view looks like that:

<%= error_messages_for ''member'' %>

<%= form.text_field :email %>
<%= form.text_area :signature %>
<%= form.has_and_belongs_to_many :preferred_music_styles %>
<%= form.belongs_to :origin_country %>

And this results in a well-known textfield and textarea for email and
signature AND in checkboxes for the habtm relation AND a dropdown select
list for the belongs_to association.

Anyway, I have adapted some code from the Rails Recipes book and it
looks like the following so far:


    def self.create_tagged_field(method_name)
      define_method(method_name) do |label, *args|
        html_surround(label, super) # Provides the HTML code that
surrounds the form label and the method (super) that generates the input
tag(s)
      end
    end

    field_helpers.reject{|h| h ==
''hidden_field''}.concat([:select]).each
do |name|
      create_tagged_field(name)
    end

    def html_surround(label, content, options = {})
      label_options = {}
      label_options[:for] = "#{@object_name}_#{label}" unless
options[:print_label_for]
      @template.content_tag(:div,
        @template.content_tag(:div,
          @template.content_tag(:label,
            nil || label.to_s.humanize, # TODO: optional argument
:caption instead of nil!
            label_options
          ), :class => :label
        ) + @template.content_tag(''div'',
        content, :class => :field), :class => :row
      )
    end

Now I''d like to offer some more options to the programmer, e.g. to set
a
custom caption instead of using the name of the database field:

<%= form.belongs_to :origin_country, :caption => ''Where do you
come
from?'' %>

Sadly I have no clue where to catch this option and remove it from the
options for further processing, because so far Rails creates a
"caption"
attribute in the input tag with the given value:

<select name="xxx" caption="Where do you come
from?">...

This is for sure not the wished effect, and it pollutes my perfectly
valid HTML code! :-)

So can anybody tell me how to

1) display this custom label instead of the default caption when this
option is set and
2) how to prevent this option from being transmitted to the later Rails
processings?

Thanks a lot for help.
Josh