【问题标题】:How to remove default input class type from Simple Form, using Rails 4 and Bootstrap 4?如何使用 Rails 4 和 Bootstrap 4 从简单表单中删除默认输入类类型?
【发布时间】:2015-12-27 17:58:47
【问题描述】:

我正在使用带有 Bootstrap 4 的 Rails 4.2.4(使用 bootstrap_ruby gem)。

简单表单向表单添加输入类型类...如果输入是字符串,它将向输入添加类string。我想知道如何阻止这种情况发生?

例如,如果我有一个带有文件输入的表单。

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

它将生成以下 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>

它将file 类添加到labelinput 字段。有没有办法在构建表单时删除file 类?

我正在尝试使用 Bootstrap 4 (Alpha),但它与 file 类名冲突。

我以为我可以在 config.wrappers 上做到这一点,但它将输入类型添加为一个类,例如。 string, file.

提前致谢。

【问题讨论】:

    标签: ruby-on-rails twitter-bootstrap ruby-on-rails-4 simple-form twitter-bootstrap-4


    【解决方案1】:

    Bootstrap 4 对自定义文件字段的命名选择很不幸,因为它非常通用。 不幸的是,没有简单的方法可以使用 SimpleForm 切换自动添加的 css 类。

    我的解决方案是引入一个新的输入字段,它只是从 FileInput 继承,所以它接收一个不同的名称和一个不同的 css 类:

    // 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
    

    将文件字段称为新输入“类型”。

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

    【讨论】:

    • 很好,谢谢。你能解释一下你的可选设置在做什么,或者举一个使用的例子吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    相关资源
    最近更新 更多