Skip to content

Instantly share code, notes, and snippets.

@HK49
Last active February 18, 2017 17:08
Show Gist options
  • Save HK49/36b3aa046c95a2711f2f6bcc4a487757 to your computer and use it in GitHub Desktop.
Save HK49/36b3aa046c95a2711f2f6bcc4a487757 to your computer and use it in GitHub Desktop.
Initializer to override default field with errors (rails 5.0.1)
<!-- path: views/layouts/ -->
<% if object.errors.any? %>
<% object.errors.full_messages.each do |msg| %>
<%=
content_tag :div, :id => "has_errors", :style => "padding:3px; margin:0 20vw; background-color:rgba(246, 138, 138, 0.7); border:solid rgba(246, 138, 138, 1) 1px; border-radius:12px; text-align:center;" do
concat(content_tag :p, msg)
end
-%>
<% end %>
<script type="text/javascript">
<%#
# this:
# window.onload = scrollToError;
# function scrollToError(){ window.location.hash = '#has_errors'; };
# or:
%>
window.onload = scrollToMiddle("#has_errors");
function scrollToMiddle(id) {
var elem_position = $(id).offset().top;
var window_height = $(window).height();
var y = elem_position - window_height/2;
window.scrollTo(0,y);
}
</script>
<% end %>
module ActiveModel::Conversion
attr_accessor :skip_field_error_wrapper
end # to skip additional class-wrapper on error
# usage:
# @user.skip_field_error_wrapper = true
# form_for(@user) do |f|...
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
class_attr_index = html_tag.index('class="')
first_tag_end_index = html_tag.index('>')
if class_attr_index.nil? || first_tag_end_index > class_attr_index
html_tag.insert(first_tag_end_index, ' class="field_error"')
elsif instance.object && instance.object.skip_field_error_wrapper
html_tag.html_safe
else
html_tag.insert(class_attr_index + 7, 'field_error ')
end
end
# compilation from http://stackoverflow.com/questions/5267998/rails-3-field-with-errors-wrapper-changes-the-page-appearance-how-to-avoid-t
<!-- examplery form -->
<% content_for :form do %>
<%= form_for(something) do |f| %>
<%= render 'layouts/error_messages', object: f.object -%>
<% end %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment