#311 Form Builders pro
Dec 26, 2011 | 12 minutes | Views, Refactoring, Forms
Forms often follow a similar pattern with a lot of repetition. Learn how to clean up form views and remove duplication with the help of form builders.
- source codeProject Files in Zip (89.7 KB)
- mp4Full Size H.264 Video (26.6 MB)
- m4vSmaller H.264 Video (14.3 MB)
- webmFull Size VP8 Video (17.1 MB)
- ogvFull Size Theora Video (32.7 MB)
Wow. Just finished it. One of your best Ryan. And this is exactly what I was looking for. I am using the Twitter Bootstrap now and I plan on wrapping all of this into a bootstrap form builder.
If you use Formtastic, there's already a gem with a custom builder for bootstrap:
simple_form does not allow all bootstrap classes.
In case anyone is wondering on how to use the custom builder by default:
ActionView::Base.default_form_builder = LabeledFormBuilder
Thanks! Now, using this method I don't need to define a wrapper class in my application_helper.rb
However, how can I add (say) a CSS class to all forms generated with this form builder?
I tried overriding the "initialize" method and editing the options[:html] hash, but this got me nowhere.
This was amazing... thanks for taking the time to explain things so clearly Ryan.
One small question: When refactoring the
collection_check_boxcode, why do you need to pass
sendmethod when calling them on
After looking at the ruby
sendmethod documentation, is it because
attributeare passed in as symbols?
How else would you do it? Hardcoding to .id and a fixed attribute name? record_id is the function name to call to get the id, it could be :id, but also any other function like :permalink for example. attribute needs to be flexible too, otherwise you could use this builder only for one fixed named attribute. Not very practical I guess... ;-)
For anyone who is interested, this is my form builder using the Twitter Bootstrap css framework.
I like the little gems (no pun intended) you pick up watching these - like this is the second or third time I've seen you use the delegate method and I'm starting to use it...
I really appreciate the thoroughness, like the delegation, the metaprogramming, and including the HABTM example from the other Railscast. Just became a subscriber and this cast was instantly actionable.
Does anyone know how to use this custom form builder with
fields_for? I've tried passing the
:builderoption, but it doesn't work.
Nevermind, it automatically works if you use nested
fields_for, like this (in Haml):
The entire form can be given a class, for instance to use twitter's bootstrap, through the following:
Is there any significant performance penalty for calling
object.class.validators_on(name).any?(below) for every field? Would it be measurably better to move this array retrieval to the form level?
Also, the snap before the delegate refactoring was awesome. Thanks Ryan!