Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Adding custom components

fionaom edited this page · 4 revisions

Adding custom components

When you use custom wrappers, you might also be looking for a way to add custom components to your wrapper. The default components are:

:label         # The <label> tag alone
:input         # The <input> tag alone
:label_input   # The <label> and the <input> tags
:hint          # The hint for the input
:error         # The error for the input

A custom component might be interesting for you if your views looks something like this:

<%= simple_form_for @blog do |f| %>
  <div class="row">
    <div class="span1 number">
      1
    </div>
    <div class="span8">
      <%= f.input :title %>
    </div>
  </div>
  <div class="row">
    <div class="span1 number">
      2
    </div>
    <div class="span8">
      <%= f.input :body, :as => :text %>
    </div>
  </div>
<% end %>

A cleaner method to create your views would be

<%= simple_form_for @blog, :wrapper => :with_numbers do |f| %>
  <%= f.input :title, :number => 1 %>
  <%= f.input :body, :as => :text, :number => 2 %>
<% end %>

To use the number option on the input you have to create a new component.

Step 1

Create an initializer file. e.g. config/initializers/simple_form/numbers_component.rb

module SimpleForm
  module Components
    # Needs to be enabled in order to do automatic lookups
    module Numbers
      # Name of the component method
      def number(wrapper_options = nil)
        @number ||= begin
          options[:number].to_s.html_safe if options[:number].present?
        end
      end

      # Used when the number is optional
      def has_number?
        number.present?
      end
    end
  end
end

SimpleForm::Inputs::Base.send(:include, SimpleForm::Components::Numbers)

Step 2

Add a new wrapper to the config/initializers/simple_form.rb file

  config.wrappers :with_numbers, :tag => 'div', :class => 'row', :error_class => 'error' do |b|
    b.use :html5
    b.use :number, :wrap_with => { :tag => 'div', :class => 'span1 number'}
    b.wrapper :tag => 'div', :class => 'span8' do |ba|
      ba.use :placeholder
      ba.use :label
      ba.use :input
      ba.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }
      ba.use :hint,  :wrap_with => { :tag => 'p', :class => 'help-block' }
    end
  end
Something went wrong with that request. Please try again.