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">
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.
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
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')
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With