Skip to content

Instantly share code, notes, and snippets.

@gambala
Created July 24, 2016 18:34
Show Gist options
  • Save gambala/095c6644a49e048ca39c4a6d92c172df to your computer and use it in GitHub Desktop.
Save gambala/095c6644a49e048ca39c4a6d92c172df to your computer and use it in GitHub Desktop.
BootstrapFormBuilder
= form_for resource do |f|
= f.form_group :first_name do
= f.label :first_name, class: 'control-label'
= f.text_field :first_name, class: 'form-control'
= f.error_message :first_name
# /config/application.rb
module ProjectName
class Application < Rails::Application
config.action_view.default_form_builder = 'BootstrapFormBuilder'
config.autoload_paths += %W(
#{config.root}/lib/form_builders
)
end
end
# /lib/form_builders/bootstrap_form_builder.rb
class BootstrapFormBuilder < ActionView::Helpers::FormBuilder
def error_message(field_name)
return if @object.errors[field_name].blank?
@template.content_tag :div, @object.errors[field_name].join(', '), class: 'help-block'
end
def form_group(field_name, options = {})
class_def = 'form-group'
class_def << ' has-error' unless @object.errors[field_name].blank?
class_def << " #{options[:class]}" if options[:class].present?
options[:class] = class_def
@template.content_tag(:div, options) { yield }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment