Can “field-with-errors” be attached to the parent of the input tag that raises the error?

强颜欢笑 提交于 2019-12-10 14:55:14

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/15627809/can-field-with-errors-be-attached-to-the-parent-of-the-input-tag-that-raises-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!