Build Bootstrap forms with simple_form in Ruby on Rails
Jan 15, 2015
I’m building Rails application which is full of many Bootstrap forms. We use placeholders instead of labels, and mostly use horizontal forms, which most of the time has more than one field on one line. Since we’re adding/editing lots of forms, to keep moving fast I made few wrappers for simple_form which allows build horizontal bootstrap forms fast.
form-group behaves as row
Please note that form-group behaves as row inside form-horizontal, so we can use all col-* classes without adding row.
One-line fields of various width
simple_form generates this wrapper to use for horizontal forms:
which is great, but it uses 9 columns as default width. But imagine this form:
It has fields of various widths. So I used this code to create wrappers for different column sizes:
So to create above form we’d write
And think how much time I saved having dozens of forms like this. (If you wonder what ig4 wrapper for, it works exactly as field4 except it’s for inline groups, I used this as reference)
Multiple fields in one line
Now let’s take a look at this form:
We have more than one fields on one line. Most of answers on SO suggested making use of CSS, which I didn’t like. So, I defined another set of wrappers for inline fields:
The most notable change here is that it doesn’t wrap fields in form-group and leaves that to us. So code of above form looks like:
I found this pretty cool. Also notice I used defaults: {wrapper: :inline_field4} instead of defining wrapper on every field.
Why I didn’t use input_field? Because that way we’d lose our sr-only labels, and I like having support for accessibility.
And if we ever need inline boolean, we’d just write