Fixing the fieldWithErrors problem on the hidden field generated by the checkbox helper: field_error_proc

Posted by Tim Connor Wed, 05 Dec 2007 18:22:00 GMT

The checkbox helper in rails inserts a zero valued hidden input to simplify the server-side value handling (for example unsetting the checkbox). The problem with this it can mess up your css on fieldWithErrors (say if you have a big red asterisk image on your error fields), because it, by definition, has the same name as the checkbox, and gets assigned the same errors. Personally, I don’t think any hidden field should show errors and thankfully rails lets me take care of that. Just put this in your environment file

#Fix problem with fieldWithErrors and the hidden field generated for a checkbox
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  if html_tag =~ /<(input)[^>]+type=["'](hidden)/
    html_tag
  elsif html_tag =~ /<(input)[^>]+type=["'](checkbox|radio)/
    "<div class=\"fieldWithErrors miniFieldWithErrors\">#{html_tag}</div>" 
  else
    "<div class=\"fieldWithErrors\">#{html_tag}</div>" 
  end
end
This is also where you could fix the whole arbitrarily inserted div messing your layouts, as well, by replacing it with a span, say. ;)
Comment form

(leave url/email »)

Help with Textile (code)