how to add a class to the input component in a wrapper in simple_form 2

前端 未结 5 1061
难免孤独
难免孤独 2021-02-04 04:57

I am trying to have class=\"text\" in my input fields when using a custom wrapper called :hinted in simple_form 2.0.0.rc

config.wrappers :hinted do          


        
5条回答
  •  迷失自我
    2021-02-04 05:42

    With :input_html works. It is a bit clunky.

    = f.input :email, :input_html => { :class => 'foo' }
    

    You can also set all the inputs on all the form elements:

    simple_form_for(@user, :defaults => { :input_html => { :class => "foo" } })
    

    But as you'd expect, this applies to everything.

    You can create custom form elements:

    # app/inputs/foo_input.rb
    class FooInput < SimpleForm::Inputs::StringInput
      def input_html_classes
        super.push('foo')
      end
    end
    
    // in your view:
    = f.input :email, :as => :foo
    

    See: https://github.com/plataformatec/simple_form/wiki/Adding-custom-input-components

    You can also create a custom form builder:

    def custom_form_for(object, *args, &block)
      options = args.extract_options!
      simple_form_for(object, *(args << options.merge(builder: CustomFormBuilder)), &block)
    end
    
    class CustomFormBuilder < SimpleForm::FormBuilder
      def input(attribute_name, options = {}, &block)
        options[:input_html].merge! class: 'foo'
        super
      end
    end
    

提交回复
热议问题