如何使用simple_form在错误输入中添加"错误"类?

Eri*_* M. 14 ruby-on-rails simple-form

我需要在呈现表单时向输入/ textarea/etc添加一个类,并且该字段有错误.

<input type="text" class="custom-error-class" />
Run Code Online (Sandbox Code Playgroud)

是否有一种简单的方法可以附加到SimpleForm的CSS类列表中,但只有在字段的相应对象出错时?

Vin*_* V. 7

我遇到了同样的问题.我的解决方案:

我创建了一个新类StringInput(它覆盖了原始类)并将实现复制出rdoc.我修补了该代码以检查字段本身是否有错误,如果是,我添加一个类无效.

因为我想使用包装器选项,所以我在我的初始化程序中添加了一个error_class属性.

完整代码:

应用程序/输入/ string_input.rb

class StringInput < SimpleForm::Inputs::StringInput
  def input(wrapper_options = nil)
    unless string?
      input_html_classes.unshift("string")
      input_html_options[:type] ||= input_type if html5?
    end

    input_html_classes << wrapper_options[:error_class] if has_errors?
    merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)

    @builder.text_field(attribute_name, merged_input_options)
  end
end
Run Code Online (Sandbox Code Playgroud)

配置/初始化/ simple_form.rb

SimpleForm.setup do |config|
  config.error_notification_class = 'alert alert-danger'
  config.button_class = 'waves-effect waves-light btn'

  config.wrappers tag: :div, class: :input, error_class: :"error-field" do |b|
    # Form extensions
    b.use :html5
    b.optional :pattern
    b.use :maxlength
    b.use :placeholder
    b.use :readonly

    # Form components
    b.use :label
    b.use :input, class: 'validate', error_class: 'invalid'
    b.use :hint,  wrap_with: { tag: :span, class: :hint }
    b.use :error, wrap_with: { tag: :span, class: :error }
  end
end
Run Code Online (Sandbox Code Playgroud)

这会在所有字符串输入上添加已定义的错误类.


vee*_*vee 1

您可以使用error_html选项来执行此操作:

<%= f.input :attr, error_html: { class: 'custom-error-class' } %>
Run Code Online (Sandbox Code Playgroud)