【问题标题】:simple_form - override default input "type" mappingsimple_form - 覆盖默认输入“类型”映射
【发布时间】:2014-12-06 11:23:38
【问题描述】:

simple_form 正在为任何整数属性的输入字段生成“type='number'”,而不是 type='text'。由于这会导致 Chrome 显示计数器控件,我宁愿让它只使用 type='text' 作为数字的默认值。

似乎可以覆盖 config/initializers/simple_form.rb 中的默认值,但从文档中不清楚如何准确执行此操作。将数字列/属性设置为呈现为 type='text' 的语法是什么?

【问题讨论】:

  • 不太明白你真正想要什么......
  • 我没有注意到输入字段被转义了,现在修复了。

标签: ruby-on-rails ruby-on-rails-4 simple-form simple-form-for


【解决方案1】:

您可以通过指定输入类型来覆盖每个字段的默认映射:

<%= f.input :age, as: :string %>

(完整的映射列表是here。)

但是,如果您想从项目中消除数字输入,请尝试:

# config/initializers/simple_form.rb (before/after the SimpleForm.setup block, if this exists) 
module SimpleForm
  class FormBuilder < ActionView::Helpers::FormBuilder
    map_type :integer, :decimal, :float, to: SimpleForm::Inputs::StringInput
  end
end

【讨论】:

  • SimpleForm::FormBuilder.mappings 在其他代码中返回 :date=&gt;SimpleForm::Inputs::StringInput, :time=&gt;SimpleForm::Inputs::StringInput, :datetime=&gt;SimpleForm::Inputs::StringInput 但是我的输入仍然是日期类型。我重新启动了服务器。
【解决方案2】:

记录在案:

使用 HTML5 日期、时间、日期时间输入

SimpleForm::Inputs::DateTimeInput.class_eval do
  def use_html5_inputs?; input_options[:html5] || true end
end

使用字符串输入日期、时间、日期时间

如果您要使用像 bootstrap-datetimepicker 这样的日期时间选择器,这很有用:

SimpleForm::FormBuilder.class_eval do
  def input(attribute_name, options = {}, &block)
    options = @defaults.deep_dup.deep_merge(options) if @defaults

    input   = find_input(attribute_name, options, &block)

    # Add native DB type as CSS class so inputs can be filtered by that
    input.input_html_classes << input.column&.type
    # Use another attribute:
    # input.input_html_options[:'data-db-type']= input.column&.type

    wrapper = find_wrapper(input.input_type, options)

    wrapper.render input
  end

  # map_type :date, :time, :datetime, to: SimpleForm::Inputs::StringInput

  alias old_default_input_type default_input_type
  def default_input_type(attribute_name, column, options)
    if column.type.in? %i(date time datetime)
      :string
    else
      old_default_input_type(attribute_name, column, options)
    end
  end
end

map_type 不需要。

【讨论】:

    猜你喜欢
    • 2012-02-20
    • 1970-01-01
    • 2019-05-09
    • 2019-01-24
    • 2012-08-21
    • 1970-01-01
    • 2019-08-17
    • 2021-12-09
    • 1970-01-01
    相关资源
    最近更新 更多