5

So I have an input element like this. The wrapping element is about, you know, a visual thing.

<div class="input-wrap">
  <input class="blah-blah" />
</div>

When the <input> contains the error, it'll be like this:

<div class="input-wrap">
  <div class="field-with-errors">
    <input class="blah-blah" />
  </div>
</div>

But what I want to do is:

<div class="input-wrap field-with-errors">
  <input class="blah-blah" />
</div>

I found this page, it's very close to my question

Rails 3: "field-with-errors" wrapper changes the page appearance. How to avoid this?

Now I know I can throw

config.action_view.field_error_proc = Proc.new { |html_tag, instance| 
   "#{html_tag}".html_safe
}

to avoid making a wrapping tag around the <input> tag that has an error on. But what I really wanna do is, again, adding "field-with-errors" class on the direct parent of the <input> tag. Can I do that? Does ActionView hold the tree structure of DOM Nodes?

Community
  • 1
  • 1
beatak
  • 9,185
  • 10
  • 33
  • 42
  • Have you found a solution ? It seems like (for a beginner like me) imposible to achieve. Probably another helper as wrapper is required – GorillaApe Feb 20 '16 at 17:26
  • There are some related questions on the side menu. There seems no straightforward solution for this yet? I dunno. http://stackoverflow.com/questions/5267998/rails-3-field-with-errors-wrapper-changes-the-page-appearance-how-to-avoid-t offers a good hint. If you can't change the template from the helper function, maybe adding a data-attribute and add the class name to the parent by JS? It sounds terrible but it may be one way to do it… – beatak Feb 23 '16 at 00:43
  • Hello @beatak , despite it was a while, have you seen [that comment](https://stackoverflow.com/questions/5267998/rails-3-field-with-errors-wrapper-changes-the-page-appearance-how-to-avoid-t/8380400#8380400) from that SO? It seems that he actually managed to do that by manipulating at the string level.. – SanjiBukai Jul 14 '17 at 06:05

1 Answers1

-2

You can put the code for handling errors wherever you like, just call it as a block on the instance variable, for example

if @instance.errors.any?
  <div class="field with errors">
  @instance.errors.full_messages.each do |msg|
    <p><%= msg %></p>
  end
end

If you user this a lot, it's good to pull it out into a helper and pass in the instance variable as a parameter.

muttonlamb
  • 6,341
  • 3
  • 26
  • 35