Skip to content

Instantly share code, notes, and snippets.

@czj
Created September 13, 2021 11:49
Show Gist options
  • Select an option

  • Save czj/1823d673b80f889f320fabf741a20bd9 to your computer and use it in GitHub Desktop.

Select an option

Save czj/1823d673b80f889f320fabf741a20bd9 to your computer and use it in GitHub Desktop.

Revisions

  1. czj created this gist Sep 13, 2021.
    43 changes: 43 additions & 0 deletions form_builder_errors.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    # 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)