Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 |b|
  b.use :input, :class => "text"
end

but the output doesn't have that class, I tried

:wrap_with => {:class => 'text'} 

to no avail

Does anyone know how this is done?

Thank You!

like image 290
Nik So Avatar asked Feb 21 '12 02:02

Nik So


3 Answers

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
like image 87
Rimian Avatar answered Nov 02 '22 02:11

Rimian


Currently there no way to do this. You can use the defaults options like this if you want.

<%= simple_form_for(@user, :defaults => { :input_html => { :class => "text" } }) do %>
  <%= f.input :name %>
<% end %>
like image 44
rafaelfranca Avatar answered Nov 02 '22 03:11

rafaelfranca


This feature is about to be merged to master right now (Oct. 2012):

https://github.com/plataformatec/simple_form/pull/622

Then you can do something like this to add HTML attributes directly on the input field:

SimpleForm.build :tag => :div, :class => "custom_wrapper" do |b|
  b.wrapper :tag => :div, :class => 'elem' do |component|
    component.use :input, :class => ['input_class_yo', 'other_class_yo']
    component.use :label, :"data-yo" => 'yo'
    component.use :label_input, :class => 'both_yo'
    component.use :custom_component, :class => 'custom_yo'
  end
end
like image 26
crispy Avatar answered Nov 02 '22 04:11

crispy