Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Rails’ form_for but set custom classes, attributes on <form> element?

form_for seems to ignore any 'extra' attributes like a data-foo attribute or class passed as options in its second argument.

= form_for @user, {:url => 'foo', :class => 'x', 'data-bar' => 'baz' } do |f|
  # ...

The output is a <form> tag with no x class or data-bar attribute.

What’s the fix?

Or, how can I grab a FormBuilder instance without using form_for?

like image 489
Alan H. Avatar asked Oct 30 '12 17:10

Alan H.


4 Answers

Use the :html hash:

= form_for @user, :html => {:class => 'x', 'data-bar' => 'baz'} do |f|

Or

= form_for @user, html: {class: 'x', data: { bar: 'baz' } } do |f|
like image 163
MurifoX Avatar answered Nov 06 '22 05:11

MurifoX


Rails 4.0.3, Ruby 2.1.0p0 -> this worked for me =>

<%= form_for(@contact, :html => {:class => 'form_height'}) do |f| %><% if     @contact.errors.any? %>
like image 40
zero_cool Avatar answered Nov 06 '22 04:11

zero_cool


I had the same problem but was puzzled that another form elsewhere in my app was working fine.

I realized that I had accidentally added a form_for inside another form_for which once removed cured the problem.

Secondly, I should add that this syntax works for me in Rails 4.2:

<%= form_for @type, html: {class: "form-horizontal"} do |f| %>

I find it preferable to the punctuation-soup of the other answers here (which were perhaps based on an older Rails version).

like image 20
MSC Avatar answered Nov 06 '22 05:11

MSC


On mostly helpers, the last arg is a hash of html options for the element.

= form_for @user, :html => {:class => 'x', 'data-bar' => 'baz'} %>

You can also check other alternatives in the documentation ActionsView::Helpers::FormHelper

like image 1
felipeclopes Avatar answered Nov 06 '22 04:11

felipeclopes