How can I add an "error" class to the input on error using simple_form?

ruby-on-rails, simple-form

Solution

I was having the same problem. My solution for this:

I created a new class StringInput (which overrides the original one) and copied the implementation out of the rdoc. I patched that code to check if there are errors on the field itself, if so I add a class invalid.

Because I wanted to use the wrapper options I added a error_class attribute into my initializer.

The full code:

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

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

This adds a defined error class onto all of your string inputs.

Problem

I need to add a class to the input/textarea/etc when the form is rendered and that field has an error. ``` <input type="text" class="custom-error-class" /> ``` Is there an easy way to append to SimpleForm's list of CSS classes, but only when the field's corresponding object is an error?

Original source