Form Horizontal with Bootstrap 3 and Simple Form 2 on Rails 4

I don’t know why this was so difficult, but I had lots of trouble getting the `form-horizontal` class to work in my rails app was quite a chore when I upgraded to bootstrap 3.  After lots of searching and hours of agony, this finally worked for me.  Credit goes to this blog post.

After you have bootstrap 3 (I use the bootstrap-sass gem) and simple_form 2, run the simple_form generator:

rails generate simple_form:install --bootstrap

So the way I understand it, this hack basically overrides the div classes in simple_form to match them up with bootstrap. So first edit the config/initializers/simple_form.rb

config.label_class = 'col-lg-2 control-label'
config.form_class = "simple_form form-horizontal"

In the config/initializers/simple_form_bootstrap.rb replace the classes “control-group” with “form-group” and replace “control” with “col-lg-10”

Now create a new initializer file, for example config/initializers/remove-this-sf_bs3_inputs.rb

inputs = %w[
CollectionSelectInput
DateTimeInput
FileInput
GroupedCollectionSelectInput
NumericInput
PasswordInput
RangeInput
StringInput
TextInput
]

inputs.each do |input_type|
superclass = “SimpleForm::Inputs::#{input_type}”.constantize

new_class = Class.new(superclass) do
def input_html_classes
super.push(‘form-control’)
end
end

Object.const_set(input_type, new_class)
end

Hopefully there will be some official support in the near future that won’t require this workaround. Let me know if you know of an easier way to get form-horizontal to work.

Here’s the Stack Overflow question that I asked regarding this problem.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: