RJS and Form Validation (Best Practice)


#1

Hello All !

I’ve been using RJS extensively, but haven’t done any form validation
with
it until now.

Should I be manually passing the RJS template some models error messages
from the controller… or
… should I be using error_messages_for in order to do the display ?

I’ve implemented the first approach, but it seems like quite a hack.
Any insight would be greatly appreciated !
Thanks !

Dylan


#2

I do it the same as with non-ajax forms, just throw your <%=
error_messages_for :model %> at the top of a form partial
If there’s an error creating, or updating the model, just
page.replace_html’id_of_el_surrounding_form_partial’, :partial =>
‘form’
That way you still get highlighting for the failed fields, and it makes
it
easy to provide a fallback if javascript is disabled.

joshua


#3

Thanks Joshua, this works perfectly.
In my case, the :partial is actually a component… and… haven’t
checked
if RJS supports :component… hmmm… I’m lazy :slight_smile:


#4

I have a feeling RJS won’t support components, and even if it did I
would
avoid using them.
Check out
http://railsexpress.de/blog/articles/2005/11/18/components-may-not-be-evil-but-they-sure-can-be-slow
You want those ajax calls to be snappy!

joshua


#5

Hi Dylan,

I added a

 
just
ahead of my form_remote_to tag helper.

Then in the action method of the form (create.rjs in my case:

if @client.errors.length > 0
page.replace_html ‘flash_box’, error_messages_for(:client)
page.show ‘flash_box’
else
page.hide ‘flash_box’
end

I got the hint from liquid’s comment to
http://rails.techno-weenie.net/question/2006/2/23/ajax_validation_flash_messages_redirects

Ed