views:

18

answers:

1

If I have a form that's on page http://foo.com/get, but posts to http://foo.com/post, what's the best way to handle displaying validation errors? I want to redirect the user back to the first page. How can I stash the form state (including error messages), so that on the next request following the redirect to http://foo.com/get I can grab that form and render it. Any ideas?

+1  A: 

You can use the session, but it takes some machinery.

On success, you store a message to display. On error, you store a message, plus a full listing of the form data entered, along with a flag for each field that is in error. The receiving page has to read this stuff from the session, do the right thing, and clear it out.

With some careful design decisions, you can avoid having to rewrite this stuff every time you have a page that displays a form. Here's more on how I accomplish this (I can't share the code itself, but it's not that good anyway):

My form validation class automatically stores the data in the session if it detects a bad submission, and my form rendering class checks for it each time it's instantiated. It will override the data from the DB (if, say, you're editing an existing record), too. My session interface automatically clears out stale messages and form data. (You have to be careful here with AJAX or other things that might clear it prematurely when accessing session info.)

grossvogel