Skip to content

Instantly share code, notes, and snippets.

@23inhouse
Created September 2, 2012 04:18
Show Gist options
  • Save 23inhouse/3594808 to your computer and use it in GitHub Desktop.
Save 23inhouse/3594808 to your computer and use it in GitHub Desktop.
Customizing simple_form and bootstrap

Customization

<%= f.input :state, :collection => ['SA', 'WA'] %>
<%= f.input :state,
            :as => :radio_buttons,
            :collection => ['SA', 'WA'],
            :item_wrapper_class => 'inline' %>
<%= f.collection_radio_buttons(:state,
  [['SA', 'SA'], ['WA', 'WA']], :first, :last) do |b|
    b.label { b.text.html_safe + ' ' + b.radio_button }
  end %>

Custom inputs

inputs are the :as thing

# config/initializers/simple_form/delegates.rb
module SimpleForm
  module Inputs
    module Delegates
      delegate :content_tag, :to => :template
      delegate :text_field, :to => :@builder
    end
  end
end
SimpleForm::Inputs::Base.send(:include, SimpleForm::Inputs::Delegates)
# app/inputs/currency_input.rb
class CurrencyInput < SimpleForm::Inputs::Base
  def input
    content_tag(:div, :class => 'input-prepend') do
      content_tag(:span, '$', :class => 'add-on') +
      text_field(attribute_name, {:class => 'currency', :size => 7}.merge(input_html_options))
    end
  end
end
f.input :money, :as => :currency

Custom components

are used in the wrappers

# config/initializers/simple_form.rb

SimpleForm.setup do |config|

  config.wrappers :bootstrap_tooltip, :tag => 'div', :class => 'control-group', :error_class => 'error' do |b|
    b.use :placeholder
    b.use :label
    b.use :tooltip
    b.wrapper :tag => 'div', :class => 'controls' do |input|
      input.use :input
      input.use :error, :wrap_with => { :tag => 'p', :class => 'help-block' }
      input.use :hint,  :wrap_with => { :tag => 'p', :class => 'help-block' }
    end
  end

end
# initializers/simple_form/tooltip_component.rb

module SimpleForm
  module Components
    module Tooltip
      def tooltip
        if options[:tooltip].present?
          tooltip = options[:tooltip]
          tooltip_content = tooltip.is_a?(String) ? tooltip : translate(:tooltips)
          tooltip_content.html_safe if tooltip_content

          template.content_tag(:span, :class => 'tooltip', :"data-content" => tooltip_content) do
            template.content_tag(:i, '', :class => 'icon-question-sign')
          end
        end
      end
    end
  end
end

SimpleForm::Inputs::Base.send(:include, SimpleForm::Components::Tooltip)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment