wcheung
wcheung

Reputation: 43

How to change the class of a label using Formtastic

I have the following code, using the latest version of Formatastic 3.1.0.

<%= f.input :name, :input_html => { :class => "col-lg-10" }, :label_html => { :class => "col-lg-2" }%>

I can change the input_html but I can't find the option to change label html class. Is there any way to do this?

The output is generated as such (note the omission of "col-lg-2" in label's class).

<li class="string input required stringish" id="account_name_input">
<label for="account_name" class="label">Name<abbr title="required">*</abbr></label>
<input id="account_name" class="col-lg-10" type="text" value="" name="account[name]">
</li>

Upvotes: 3

Views: 1518

Answers (1)

februaryInk
februaryInk

Reputation: 725

Looking through the documentation and the source code, I don't see a built-in way to do this. (I could always be wrong.) However, perhaps this monkey-patch will work:

config/initializers/formtastic_monkey_patch.rb

Formtastic::Inputs::Base::Labelling.module_eval do

  def label_html_options
    {
      :for => input_html_options[:id],
      :class => (['label'] + (options[:label_class] || [])).flatten
    }
  end
end

This should override Formtastic's default label_html_options function, which can be seen in this file. Classes would then be added through an array:

f.input :my_attribute, :label_class => ['my_class', 'my_other_class']

That's my idea, but I'd suggest getting an opinion apart from mine before using it.

Upvotes: 2

Related Questions