How to remove default input class type from Simple

2019-08-08 19:35发布

问题:

I'm using Rails 4.2.4 with Bootstrap 4 (using the bootstrap_ruby gem).

Simple Form adds input type classes to the form... if the input is a string it will add a class string to the input. I wanted to know how to stop this from happening?

For example, if I had a form with a file input.

simple_form_for @attachment do |f|
  f.input_field :file, as: :file
end

It will produce the following HTML:

<form>
  ...

  <div class="form-group file optional photo_image">
    <label class="file optional control-label" for="attachment_file">File</label>
    <input class="file optional" type="file" name="attachment[file]" id="attachment_file"></div>

  ...

</form>

It adds the file class to the label and input fields. Is there a way to remove the file class when the form is being built?

I'm trying to use Bootstrap 4 (Alpha) and it's clashing with the file class name.

I thought I could do it on the config.wrappers but it adds the type of input as a class eg. string, file.

Thanks in advance.

回答1:

Bootstrap 4's naming choice on the custom file field is unfortunate, as it is very generic. Unfortunately, there is no easy way to toggle that automatically added css-classes with SimpleForm.

My solution is to introduce a new input field which just inherits from the FileInput, so it receives a different name and so a different css-class:

// initializer
# create a new file_hack input type same as file

class SimpleForm::Inputs::FileHackInput < SimpleForm::Inputs::FileInput
end

# optional: map file_hack to a input type configuration for easier classes etc.
SimpleForm.setup do |config|
  ...
  config.wrapper_mappings = {
     # check_boxes: :vertical_radio_and_checkboxes,
     # radio_buttons: :horizontal_radio_and_checkboxes,
     # file: :vertical_file_input,
     file_hack: :vertical_file_input,
     # boolean: :vertical_boolean
  }

  config.wrappers :vertical_file_input, tag: 'fieldset', class: 'form-group', error_class: 'has-error' do |b|
    b.use :html5
    b.use :placeholder
    b.use :label, class: 'control-label'

    b.wrapper tag: 'div' do |ba|
      ba.use :input, class: 'form-control-file'
      ba.use :error, wrap_with: { tag: 'span', class: 'help-block' }
      ba.use :hint,  wrap_with: { tag: 'div', class: 'text-muted' }
    end
  end

Call the file field as the new input "type".

// form
= f.input :file, as: :file_hack