fieldWithErrors

Posted on March 25, 2007

I came across a way to overwrite the default fieldWithErrors div that gets created when an input field has an error. Someone else might have already discussed this or has a better way. But I thought I would share what I came up with.

The code that creates the fieldWithErrors div around an input field with errors associated with it is defined in active_record_helper.rb file and it looks like:

  module ActionView
    class Base
      @@field_error_proc = 
              Proc.new{ |html_tag, instance| "<div class=\"fieldWithErrors\">#{html_tag}</div>" }
      cattr_accessor :field_error_proc
    end
    ...
  end

In my config/environment.rb file, I overwrite the behaviour like so:

  ActionView::Base.field_error_proc = 
           Proc.new{ |html_tag, instance| "<span class=\"field_with_errors\">#{html_tag}</span>" }
Comments
  1. corbanbrookApril 19, 2007 @ 05:33 PM

    Im trying to figure out how to have the fieldWithErrors class applied directly to the form tag.

    you could have solved the above problem by simply adding display: inline; to the error style so the div acted like a span.

  2. Graeme NelsonApril 19, 2007 @ 06:13 PM

    Corban – I could have added display: inline; in my css file. however, the fieldWithErrors doesn’t match our current naming scheme in the css file. We like to use something like field_with_errors instead of fieldWithErrors.

    In regards, to applying the class directly to the form, you could create your own form builder that could check to see if the model has any errors.