诗歌rails之自定义field_error

action_view/helpers/active_record_helper.rb里的一段代码:
ruby代码
  1. module ActionView  
  2.   class Base  
  3.     @@field_error_proc = Proc.new{ |html_tag, instance| "<div class=\"fieldWithErrors\">#{html_tag}</div>" }  
  4.     cattr_accessor :field_error_proc  
  5.   end  
  6.   
  7.   module Helpers  
  8. ...  
  9.     class InstanceTag  
  10.       def error_wrapping(html_tag, has_error)  
  11.         has_error ? Base.field_error_proc.call(html_tag, self) : html_tag  
  12.       end  
  13.     end  
  14.   
  15.   end  
  16. end  
module ActionView class Base @@field_error_proc = Proc.new{ |html_tag, instance| "<div class=\"fieldWithErrors\">#{html_tag}</div>" } cattr_accessor :field_error_proc end module Helpers ... class InstanceTag def error_wrapping(html_tag, has_error) has_error ? Base.field_error_proc.call(html_tag, self) : html_tag end end end end 
我们看到,我们的输入框被一个class为fieldWithErrors的div框包围了,当该field出错时我们可以使用css控制显示效果
如果我们想自定义field_error也是很简单的:
ruby代码
  1. # environment.rb  
  2. ActionView::Base.field_error_proc = Proc.new do |html_tag, instance_tag|  
  3.   "<span class='field_error'>#{html_tag}</span>"  
  4. end  
# environment.rb ActionView::Base.field_error_proc = Proc.new do |html_tag, instance_tag| "<span class='field_error'>#{html_tag}</span>" end 
因为field_error_proc是一个类变量(两个@开头),所以我们可以在environment.rb里修改它
Java代码
  1. ActionView::Base.field_error_proc = Proc.new {|html_tag, instance|  
  2.   %(  
  3.   #{html_tag}  
  4.     
  5.   )  
Java代码
  1. ActionView::Base.field_error_proc = Proc.new {|html_tag, instance|
  2. %(
  3. #{html_tag}
  4. )

8.3 Customizing the Error Messages HTML

By default, form fields with errors are displayed enclosed by a div element with the fieldWithErrors CSS class. However, it’s possible to override that.

The way form fields with errors are treated is defined by ActionView::Base.field_error_proc. This is a Proc that receives two parameters:

* A string with the HTML tag
* An instance of ActionView::Helpers::InstanceTag.

Here is a simple example where we change the Rails behaviour to always display the error messages in front of each of the form fields with errors. The error messages will be enclosed by a span element with a validation-error CSS class. There will be no div element enclosing the input element, so we get rid of that red border around the text field. You can use the validation-error CSS class to style it anyway you want.
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance| if instance.error_message.kind_of?(Array) %(#{html_tag}  #{instance.error_message.join(',')}) else %(#{html_tag}  #{instance.error_message}) end end

This will result in something like the following:



Validation error messages

posted @ 2009-07-08 14:39  麦飞  阅读(325)  评论(0编辑  收藏  举报