Skip to content

Instantly share code, notes, and snippets.

@crosebrugh
Last active August 29, 2015 14:05
Show Gist options
  • Save crosebrugh/4c873042d54850076506 to your computer and use it in GitHub Desktop.
Save crosebrugh/4c873042d54850076506 to your computer and use it in GitHub Desktop.
Vector simple_form error notification to flash
# A https://github.com/plataformatec/simple_form puts it's alert box inside of the form instead
# of using the flash object. This may look clunky depending on how the various backgrounds are set up on the page.
# E.g. in a view, f.error_notification puts the alert within the form instead of above
# it where flash info goes as per the layout
<%= simple_form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f| %>
<%= f.error_notification %>
<%= f.full_error :confirmation_token %>
<div class="form-inputs">
<%= f.input :email, required: true, autofocus: true %>
</div>
<div class="form-actions">
<%= f.button :submit, "Send confirmation instructions", class: "btn-large btn-submit" %>
</div>
<%= render "devise/shared/nav" %>
<% end %>
# By deriving a custom form builder class and overriding a few things we can easily stick these
# messages in the flash object insted and handle their output in the layout file.
# Here are the files neeeded:
# config/initializers/z300_custom_form.rb
require 'custom_form'
module SimpleForm::ActionViewExtensions::FormHelper
def simple_form_for_with_custom(object, *args, &block)
options = args.extract_options!
simple_form_for_without_custom(object, *(args << options.merge(builder: ::CustomForm::FormBuilder)), &block)
end
alias_method_chain :simple_form_for, :custom
end
# lib/custom_form.rb
require 'simple_form'
require 'custom_form/form_builder'
require 'custom_form/error_notification'
module CustomForm
end
# lib/custom_form/error_notification.rb
module CustomForm
class ErrorNotification < SimpleForm::ErrorNotification
def render
if has_errors?
# put message right into the flash instedd of rendering it into a div within the form
template.flash.now[:alert] = error_message
end
''
end
protected
def translate_error_notification
lookups = []
lookups << :"#{object_name}"
lookups << :default_message
lookups << "Please review the problems below:"
# added :count option so the message is properly pluralized
I18n.t(lookups.shift, scope: :"simple_form.error_notification", default: lookups, count: errors.count)
end
end
end
# config/locales/simple_form.en.yml
en:
simple_form:
error_notification:
default_message: # remove message from here and nest the variants by counta
zero: ''
one: "Please fix the highlighted issue"
other: "Please fix the highlighted issues"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment