4

How do you add an additional class to a rails generated form? This is as opposed to overwriting the existing class as explained here:

How do you override the class name in the form_for helper?

Using :class => "foo" does not work.

Community
  • 1
  • 1
tks
  • 745
  • 9
  • 31
  • 1
    Why don't you just add the original class in manually and do it that way? – Bradley Priest Feb 22 '12 at 23:46
  • The html for the form element is generated by the rails helper, so it doesn't have a preexisting class, only what you give it. Are you using formtastic or some other type of gem that affects the form code? And when you say that `:class => "foo"` does not work, do you mean that it doesn't assign the class "foo" to the element at all? – ellawren Feb 23 '12 at 00:31
  • @Bradley, I could do that but it's ugly so i thought there would be a better way. – tks Feb 23 '12 at 07:36
  • @ellawren, actually no the default rails form helper does assign a default class, I think it is {resource name}_new, and :class => "foo" has no effect – tks Feb 23 '12 at 07:37
  • You should probably post the code you're using to generate the form... – ellawren Feb 23 '12 at 16:04
  • Thanks, I just did it with the manual addition, was just surprised since I though :class => was a pretty established convention so wanted to make sure I wasnt missing anything. – tks Feb 23 '12 at 20:15
  • 1
    Does anyone have a solution for this other than doing it manually? I have the same problem: `form_for(resource)`automatically adds the appropriate class (e.g. new_resource or edit_resource). But `form_for(resource, {html:{class:'myclass'}})` **overrides** the above class and just outputs 'myclass'. How can I **add** 'myclass' to the Rails-generated class 'new_resource' or 'edit_resource' on the form? – morgler Feb 12 '13 at 13:24
  • One way you can do it is with something like `html: { class: "#{dom_class(resource, action_name)} myclass" }`. `dom_class` is the method that `form_for` calls internally (through `apply_form_for_options!`). Problem with using `action_name` is that it will change if the form is rerendered by a different action, ie. `create` or `update` if there are validation errors. – Inkling Sep 05 '14 at 05:25

1 Answers1

0

Following the comment's advice I did this via manual addition of the original class

tks
  • 745
  • 9
  • 31