Nested_Form meets Twitter Bootstrap using twitter_bootstrap_form_for

I have been playing pretty heavily with twitter bootstrap lately and while incorporating it into an existing site found that I couldn’t use the great twitter_bootstrap_form_for gem with nested_form.

Doing a little digging I found how nested_form handles various builders.

So getting to the how to:

In your Gemfile add:


gem 'twitter_bootstrap_form_for'
gem 'nested_form', :git => 'git://github.com/ryanb/nested_form.git'

After doing a bundle install to get the code. We are using the HEAD version of nested_form because support for other builders is not in the released version yet.

Now we need an initializer to add some methods.


require 'nested_form/builder_mixin'

module NestedForm
  begin
    require 'twitter_bootstrap_form_for'
    class TwitterBootstrapBuilder < ::TwitterBootstrapFormFor::FormBuilder
      include ::NestedForm::BuilderMixin
    end
  rescue LoadError
  end
  
  module ViewHelper
    if defined?(TwitterBootstrapBuilder)
      def bootstrap_nested_form_for(*args, &block)
        options = args.extract_options!.reverse_merge(:builder => NestedForm::TwitterBootstrapBuilder)
        form_for(*(args << options), &block) << after_nested_form_callbacks
      end
    end
  end
  
end

Now when you want to use nested_form and the twitter_bootstrap_form_for syntax you can by using
bootstrap_nested_form_for where you would normally use form_for.

See the documentation for nested_form and for twitter_bootstrap_form_for for details on how those libraries work.

This entry was posted in Ruby on Rails. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Spam Protection by WP-SpamFree