Rails - Custom Form Builder


/ Published in: Rails
Save to your folder(s)



Copy this code and paste it in your HTML
  1. class ErrorFormBuilder < ActionView::Helpers::FormBuilder
  2. #Adds error message directly inline to a form label
  3. #Accepts all the options normall passed to form.label as well as:
  4. # :hide_errors - true if you don't want errors displayed on this label
  5. # :additional_text - Will add additional text after the error message or after the label if no errors
  6. def label(method, text = nil, options = {})
  7. #Check to see if text for this label has been supplied and humanize the field name if not.
  8. text = text || method.to_s.humanize
  9. #Get a reference to the model object
  10. object = @template.instance_variable_get("@#{@object_name}")
  11.  
  12. #Make sure we have an object and we're not told to hide errors for this label
  13. unless object.nil? || options[:hide_errors]
  14. #Check if there are any errors for this field in the model
  15. errors = object.errors.on(method.to_sym)
  16. if errors
  17. #Generate the label using the text as well as the error message wrapped in a span with error class
  18. text += " <span class=\"error\">#{errors.is_a?(Array) ? errors.first : errors}</span>"
  19. end
  20. end
  21. #Add any additional text that might be needed on the label
  22. text += " #{options[:additional_text]}" if options[:additional_text]
  23. #Finally hand off to super to deal with the display of the label
  24. super(method, text, options)
  25. end
  26. end

URL: http://ramblingsonrails.com/how-to-make-a-custom-form-builder-in-rails

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.