Skip to content

Instantly share code, notes, and snippets.

@willywos
Created August 31, 2012 15:49
Show Gist options
  • Save willywos/3554919 to your computer and use it in GitHub Desktop.
Save willywos/3554919 to your computer and use it in GitHub Desktop.
Add required mark to methods in a form.
#config/initializers/form_builder.rb
class ActionView::Helpers::FormBuilder
alias :orig_label :label
def label(method, content_or_options = nil, options = nil, &block)
if content_or_options && content_or_options.class == Hash
options = content_or_options
else
content = content_or_options
end
#This looks to see if allow blank is turned onn/of for the
#attribute. Default it's set to true.
allow_blank = true
object.class.validators_on(method).map(&:options).each { |field_option|
unless field_option.empty?
if field_option.has_key?(:allow_blank)
allow_blank = field_option[:allow_blank]
end
end
}
#puts "method:#{method}"
#puts "allow_blank:#{allow_blank}"
required_mark = ''
required_mark = '<div class="required-field-icon"><i class="icon-exclamation-sign"></i></div>' if object.class.validators_on(method).map(&:class).include? ActiveModel::Validations::PresenceValidator
required_mark = '<div class="required-field-icon"><i class="icon-exclamation-sign"></i></div>' if object.class.validators_on(method).map(&:class).include?(ActiveModel::Validations::InclusionValidator) && !allow_blank
content ||= method.to_s.humanize
content = (content + required_mark).html_safe
self.orig_label(method, content, options || {}, &block)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment