field_error_proc.rb 990 B

123456789101112131415161718192021222324252627
  1. ## Overriding ActionView::Base.field_error_proc in Rails
  2. ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  3. html = %(<div class="field_with_errors">#{html_tag}</div>).html_safe
  4. # add nokogiri gem to Gemfile
  5. form_fields = [
  6. 'textarea',
  7. 'input',
  8. 'select'
  9. ]
  10. elements = Nokogiri::HTML::DocumentFragment.parse(html_tag).css "label, " + form_fields.join(', ')
  11. elements.each do |e|
  12. if e.node_name.eql? 'label'
  13. html = %(<div class="has-error">#{e}</div>).html_safe
  14. elsif form_fields.include? e.node_name
  15. if instance.error_message.kind_of?(Array)
  16. html = %(<div class="has-error">#{html_tag}<span class="help-block">&nbsp;#{instance.error_message.uniq.join(', ')}</span></div>).html_safe unless html_tag =~ /hidden/
  17. else
  18. html = %(<div class="has-error">#{html_tag}<span class="help-block">&nbsp;#{instance.error_message}</span></div>).html_safe unless html_tag =~ /hidden/
  19. end
  20. end
  21. end
  22. html
  23. end