Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Putting the errors in the right place (See related posts)

The idea is to display the error near the field instead of in global area at the top of the page.
Simple… first go into your view and delete the
error_messages_forobject’


Then stick this in your application helper.


# application_helper.rb
def error_for(object, method = nil, options={})
if method
err = instance_variable_get("@#{object}").errors.on(method).to_sentence rescue instance_variable_get("@#{object}").errors.on(method)
else
err = @errors["#{object}"] rescue nil
end
options.merge!(:class=>’fieldWithErrors’,
:id=>"#{[object,method].compact.join(’_')}-error",
:style=>(err ? #{options[:style]}":"#{options[:style]};display: none;")
)
content_tag("p",err || "", options )
end


Then in your form view, add an ‘error_for’ call wherever you need one…

# _form.rhtml
  <p><label for="code_project_name">Name</label>
  <%= text_field ‘code_project’, ‘name’  %>
  <%= error_for ‘code_project’, ‘name’ %></p>


If the model fails a validation test, then it will show the message right next to the field that caused the validation problem.
Also note that if you define an instance variable called @errors containing a hash of field_names and messages, they will also be used. This is handy for those form fields that don’t correspond to a model attribute.

Comments on this post

jlong posts on Feb 01, 2007 at 14:45
This works well for me:

ActionView::Base.field_error_proc = Proc.new do |html, instance|
  %{<div class="error-with-field">#{html} <small class="error">&bull; #{[instance.error_message].flatten.first}</small></div>}
end
ingoweiss posts on Feb 02, 2007 at 16:09
Hi Mickael, isn't that what the built-in error_message_on method is for? Maybe I'm missing something...

You need to create an account or log in to post comments to this site.


Click here to browse all 4852 code snippets

Related Posts