This method was tested on Rails 2.2.2.
I am currently building a Rails application where I will need to build some custom form elements and have them still work with the FormBuilder.
I found a post about building a spinbox field that really helped me on my way.
In my application I had a boolean field in the database and I wanted to create a menu select with the options 'Yes' and 'No' with a corresponding '1' or '0' value. I also wanted the option to include the ability to add a blank option as a default using the include_blank syntax that is also found in the DateHelper. For example;
:include_blank => true
OR
:include_blank => ' - Any - '
This would provide me with the normal flexibility of the default select tag.
For my project I need to extend the FormOptionsHelper.
what to do
I started off by creating a file in the lib folder:
my_form_options_helper.rb
-
module ActionView
-
module Helpers
-
module FormOptionsHelper
-
def boolean_yes_no_select(object_name, method, options = {}, html_options = {})
-
choices = {
-
'No' => false,
-
'Yes' => true
-
}
-
InstanceTag.new(object_name, method, self, options.delete(
bject)).to_select_tag(choices, options, html_options) -
end
-
end
-
-
class FormBuilder
-
def boolean_yes_no_select(method, options = {}, html_options = {})
-
@template.boolean_yes_no_select(@object_name, method, objectify_options(options), @default_options.merge(html_options))
-
end
-
end
-
end
-
end
Next will need to add a line to your 'environment.rb' file:
-
require 'my_form_options_helper'
This makes the 'boolean_yes_no_select available to your form builder and it allows you to create them independantly of a form builder.
Using it with the form_for method is easy:
-
f.boolean_yes_no_select :publish, :include_blank => "Any"
I hope this will help others in their rails development.
Development Rails