Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a class to a form in ruby on rails without setting / overriding the existing default helper class?

Adding a class for form_for through the html: {class: "form-horizontal"} option overrides the default new_model or edit_model class. How do I add my class while keeping the existing form_helper class?

I want:

<form class="edit_model form-horizontal"> or

<form class="new_model form-horizontal">

Instead of:

<form class="form-horizontal">

like image 841
Evan Avatar asked May 31 '12 18:05

Evan


3 Answers

I ran into exactly the same issue. Eventually, I came up with this solution

form_for @foo, :html => {:class => "form-horizontal #{controller.action_name}_model_name"}

It might be a little too late for this to be of much use to you, but maybe someone else will find it useful.

like image 181
sjobe Avatar answered Oct 23 '22 07:10

sjobe


Defining classes via the :html => {:class => '...'} option overrides any classes added by the default builder. However, you can append CSS classes within the block without overriding those classes.

With the form_for helper, the :class will be a string if not otherwise set. Note the leading space when appending. (Update: also note that the string will be frozen in recent versions of Rails, so += must be used instead of << to avoid a "can't modify frozen String" error.)

<%= form_for @model do |f| %>
  <% f.options[:html][:class] += ' form-horizontal' %>
  <%# ... %>
<% end %>

<form class="edit_model form-horizontal">

If you're using the simple_form_for helper, options[:html][:class] will be an array, and you don't need the extra leading space (although it doesn't hurt).

<%= simple_form_for @model do |f| %>
  <% f.options[:html][:class] << 'form-horizontal' %>
  <%# ... %>
<% end %>

<form class="simple_form edit_model form-horizontal">

If you're using a symbol instead of a model, form_for will not set the class, and options[:html][:class] will be nil in the block. But if you're doing this you don't have a model to be new or persisted anyway.

<%= form_for :model do |f| %>
  <% f.options[:html][:class] << ' form-horizontal' %>
  <%# ... %>
<% end %>

NoMethodError: undefined method `<<' for nil:NilClass
like image 25
Steve Avatar answered Oct 23 '22 07:10

Steve


Maybe not an ideal solution, but have you considered doing it with JS/Jquery?

For example:

$(document).ready(function(){
    $('form.edit_model').addClass('form-horizontal')
});
like image 28
abhir Avatar answered Oct 23 '22 06:10

abhir