Skip to content

Instantly share code, notes, and snippets.

@scmx
Created May 23, 2014 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scmx/80f9794cf7fd9cd45d26 to your computer and use it in GitHub Desktop.
Save scmx/80f9794cf7fd9cd45d26 to your computer and use it in GitHub Desktop.
BootstrapFormBuilder #rails #bootstrap3 #has-error, based on http://stackoverflow.com/a/22183501
#
# Bootstrap 3 integration for rails form_for
#
class BootstrapFormBuilder < ActionView::Helpers::FormBuilder
# Creates a .form-group which adds .has-error automatically
# Usage:
# <%= f.form_group :attribute_name %>
# Result:
# <div class="form-group has-error" />
# http://stackoverflow.com/a/22183501
def form_group(method, options = {})
class_def = 'form-group'
class_def << ' has-error' unless @object.errors[method].blank?
class_def << " #{options[:class]}" if options[:class].present?
options[:class] = class_def
@template.content_tag(:div, options) { yield }
end
# Creates a .help-text for every error when there are errors
# Usage:
# <%= f.help_text :attribute_name %>
# Result:
# <span class="help-text">Email måste anges</span>
# <span class="help-text">Email är fel</span>
def help_text(method, options = {})
return unless @object.errors[method].any?
@object.errors.full_messages_for(method).map { |error|
@template.content_tag(:span, error, class: 'help-block')
}.join.html_safe
end
# Creates a .alert when errors are available
# Usage:
# <%= f.alert_danger :attribute_name %>
# Result:
# <div class="alert alert-danger">2 fel förhindrade denna ...</div>
def alert_danger(options = {})
return unless @object.errors.any?
model = I18n.t("activerecord.models.#{@object.class.to_s.underscore}")
text = I18n.t("activerecord.errors.template.header",
model: model,
count: @object.errors.full_messages.count)
@template.content_tag(:div, text, class: "alert alert-danger").html_safe
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment