I wanted to have data-error
on the form field instead of the standard rails error wrapper <div class="field_with_errors"></div>
. With a data attribute we can do some much nicer handling of the form field.
You just need to create this initializer:
# e.g. config/initializers/form_field_data_error_attribute.rb
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if html_tag =~ /<(input|label|textarea|select)/
html_field = Nokogiri::HTML::DocumentFragment.parse(html_tag)
html_field.children.each do |c|
c['data-error'] = instance.error_message.uniq.join(', ')
end
html_field.to_s.html_safe
else
html_tag
end
end
Now fields with errors just have the data-error
attribute. Super easy to work with, and setting up proper CSS and tooltip behavior.