诗歌rails之自定义field_error
- 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
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也是很简单的:
- # environment.rb
- ActionView::Base.field_error_proc = Proc.new do |html_tag, instance_tag|
- "<span class='field_error'>#{html_tag}</span>"
- 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里修改它
- ActionView::Base.field_error_proc = Proc.new {|html_tag, instance|
- %(
- #{html_tag}
-
- )
- ActionView::Base.field_error_proc = Proc.new {|html_tag, instance|
- %(
- #{html_tag}
- )
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