Created
February 8, 2009 11:39
-
-
Save jzajpt/60353 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LabeledFormBuilder < ActionView::Helpers::FormBuilder | |
%w[text_field collection_select select date_select password_field | |
text_area].each do |method_name| | |
alias :"plain_#{method_name}" :"#{method_name}" | |
# Define field helper without label | |
define_method(:"#{method_name}_without_label") do |field_name, *args| | |
field_content_tag(send(:"plain_#{method_name}", field_name, *args) + | |
field_error(field_name)) | |
end | |
# Define full-blown field helper (with label and error message) | |
define_method(method_name) do |field_name, *args| | |
field_content_tag(field_label(field_name, *args) + super + field_error(field_name)) | |
end | |
end | |
alias :plain_check_box :check_box | |
def check_box(field_name, *args) | |
field_content_tag(super + " " + field_error(field_name) + field_label(field_name, *args), | |
:class => 'form-field checkbox') | |
end | |
alias :plain_submit :submit | |
def submit(*args) | |
field_content_tag(super, :class => 'form-control') | |
end | |
def field_content_tag(content = nil, options = {}) | |
options.reverse_merge! :class => 'form-field' | |
@template.content_tag(:div, content, options) | |
end | |
private | |
def field_error(field_name) | |
if object.errors.invalid? field_name | |
@template.content_tag(:span, [object.errors.on(field_name)].flatten.first.sub(/^\^/, ''), :class => 'error_message') | |
else | |
'' | |
end | |
end | |
def field_label(field_name, *args) | |
options = args.extract_options! | |
options[:label_class] = "required" if options[:required] | |
label(field_name, options[:label], :class => options[:label_class]) | |
end | |
def objectify_options(options) | |
super.except(:label, :required, :label_class) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment