3
votes

We would like to use bootstrap span6 in our simple_form. Here is what we are doing now:

<%= simple_form_for(@customer, :html => {:class => 'form-horizontal'}) do |f| %>    

  <%= f.input :name, :label => t('CompanyName:'), :input_html => { :class => "span6" } %>  
  <%= f.button :submit, t('Save') , :class => BUTTONS_CLS['action'] %>  
<% end %> 

The problem is that we need add :input_html => {:class => 'span6'} to each and every f.input and there are quite a lot of simple_forms in our rails app. Is there a way we can assign once span6 and apply it to all simple form in the app? Or we have to go one by one to add the input_html => {} to each f.input.

2

2 Answers

3
votes

You can put the default class for different elements like button, label, input etc in the simple form configuration file -> config/initializers/simple_form.rb

SimpleForm.setup do |config|
  config.form_class = :simple_form
  config.input_class = :input_class
end

Please refer to this sample file for more configuration options

3
votes

The config.input_class option mentioned in the other answer was introduces after the release of 2.1.0. That's why you get an error. Using the latest gem version from Github would solve the problem but this version requires Rails 4.

You can override the default behaviour by appending something like this to config/initializers/simple_form.rb:

%w(StringInput RangeInput CollectionSelectInput GroupedCollectionSelectInput PasswordInput TextInput NumericInput).each do |class_name|
  old_class = "SimpleForm::Inputs::#{class_name}".constantize
  new_class = Class.new(old_class) do
    def input_html_classes
      super.push('span6')
    end
  end
  Object.const_set(class_name, new_class)
end

Explanation for the code: I used a bit of metaprogramming in order to avoid writing almost the same code seven times. So this code does the following:

  1. It iterates through the array of names of classes that represent various types of fields.
  2. Next, it uses String#constantize method provided by ActiveSupport to get a class by its name.
  3. Next, it dynamically creates a class using Class#new (a param passed to Class#new is an ancestor class) and defines input_html_classes method inside it.
  4. Next, it assigns a name to a newly created class.

Finally we have seven classes StringInput, RangeInput etc with overriden input_html_classes method.