开发者

When a form doesn't post to the page it's on, what's the best way to pass the error state back?

开发者 https://www.devze.com 2023-01-05 13:00 出处:网络
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 w开发者_如何学Pythonant to redirect the user back t

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 w开发者_如何学Pythonant 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?


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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消