SimpleForm default input class

2020-04-07 19:18发布

问题:

I'm using SimpleForm + Bootstrap. How can I add an attribute to all type="text" inputs with class = span12?

Something that outputs something like this:

<div class="controls"><input autofocus="autofocus" class="string required span12" id="user_first_name" name="user[first_name]" required="required" size="50" type="text" value=""></div>

I tried playing with config.wrappers but this

ba.use :input,  :wrap_with => { :class => 'span12' }

doesn't work. It adds to wrapper instead of modifying the input tag. Any thoughts?

SimpleForm.setup do |config|
  config.wrappers :bootstrap, :tag => 'div', :class => 'control-group', :error_class => 'error' do |b|
    b.use :html5
    b.use :placeholder
    b.use :label
    b.wrapper :tag => 'div', :class => 'controls' do |ba|
      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
  config.default_wrapper = :bootstrap
end

回答1:

I had a similar issue and after some research I found out that this is not supported using the wrapper api.

The best you can do is use the :defaults option in each form, instead of adding for every input.

https://github.com/plataformatec/simple_form/issues/754

You can achieve this like this: simple_form_for(@my_instance, defaults: { input_html: { class: 'span12' }})

You can also choose to use a custom formbuilder. https://github.com/plataformatec/simple_form#custom-form-builder



回答2:

You can simply override the simple_form default for string input by adding a string_input.rb class file to your rails load path (i.e. app/inputs/string_input.rb) and include as follow:

class StringInput < SimpleForm::Inputs::StringInput
  def input_html_classes
    super.push('span12')
  end
end

If you need to add more default classes to other types of input, you can check out the various input types provided:

https://github.com/plataformatec/simple_form/tree/master/lib/simple_form/inputs