Skip to content

Instantly share code, notes, and snippets.

@seyhunak
Created December 29, 2011 02:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seyhunak/1531200 to your computer and use it in GitHub Desktop.
Save seyhunak/1531200 to your computer and use it in GitHub Desktop.
BootstrapFormBuilder
class BootstrapFormBuilder < 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
helpers.each do |name|
define_method(name) do |field, *args|
options_index = ActionView::Helpers::FormBuilder.instance_method(name.to_sym).parameters.index([:opt,:options])
if options_index.nil?
options = args.last.is_a?(Hash) ? args.pop : {} # pretty sure this shouldn't happen
else
options = args[options_index - 1] # -1 to account for the method name argument
end
label = label(field, options[:label], :class => options[:label_class])
@template.content_tag(:div, :class => 'clearfix') do
@template.concat(label)
@template.concat(@template.content_tag(:div, :class => 'input') { @template.concat(super(field, *args)) })
end
end
end
end
ActionView::Base.default_form_builder = BootstrapFormBuilder
def bootstrap_form_for(object, options = {}, &block)
options[:builder] = BootstrapFormBuilder
form_for(object, options, &block)
end
@seyhunak
Copy link
Author

class BootstrapFormBuilder < ActionView::Helpers::FormBuilder
['text_field', 'text_area'].each do |helper|
define_method helper do |field, *args|
options = args.detect{ |a| a.is_a?(Hash) } || {}

if @object.errors[field].any?
'

'.html_safe +
(self.label field) +
'
'.html_safe +
(super field, *args) +
''.html_safe + @object.errors[field].join('; ') + ''.html_safe +
'
'.html_safe
else
'
'.html_safe +
(self.label field) +
'
'.html_safe +
(super field, *args) +
'
'.html_safe
end
end
end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment