Created
September 13, 2021 11:49
-
-
Save czj/1823d673b80f889f320fabf741a20bd9 to your computer and use it in GitHub Desktop.
Rails 6+ helpers to display a list of form errors, adapted for Bootstrap 5 syntax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# Nifty Generators - https://github.com/ryanb/nifty-generators | |
# | |
# copy from Nifty Generators, | |
# markup optimized for bootstrap | |
# | |
# Usage: | |
# <%= f.error_messages %> | |
# <%= error_messages_for(@object) %> | |
# | |
# Markup aligned with bootstrap 5 | |
module ErrorMessagesHelper | |
# Render error messages for the given objects. The :message and :header_message options are allowed. | |
def error_messages_for(*objects) | |
options = objects.extract_options! | |
options[:template_header] ||= I18n.t("errors.template.header", count: objects[0].errors.size, model: objects[0].class.model_name.human) | |
options[:template_body] ||= I18n.t("errors.template.body") | |
messages = objects.compact.flat_map { |o| o.errors.full_messages } | |
return if messages.empty? | |
content_tag(:div, class: "alert alert-danger alert-form alert-dismissible d-flex align-items-center") do | |
content_tag(:div, class: "flex-shrink-0") do | |
fa_icon("fas-exclamation-triangle", size: "3x") | |
end + | |
content_tag(:div, class: "flex-grow-1 ms-3") do | |
list_items = messages.map { |msg| content_tag(:li, msg) } | |
content_tag(:button, nil, class: "btn-close", "data-bs-dismiss": "alert") + | |
content_tag(:h6, options[:template_header], class: "text-uppercase text-reset my-1") + | |
content_tag(:p, options[:template_body]) + | |
content_tag(:ul, list_items.join.html_safe, class: "mb-0") | |
end | |
end | |
end | |
module FormBuilderAdditions | |
def error_messages(options = {}) | |
@template.error_messages_for(@object, options) | |
end | |
end | |
end | |
ActionView::Helpers::FormBuilder.send(:include, ErrorMessagesHelper::FormBuilderAdditions) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment