CakePHP 元素错误处理问题

2021-12-21 00:00:00 validation php cakephp

我在引用用户控制器和 login() 和 register() 操作的元素中有我的登录和注册表单.例如,当我在模态或页面控制器操作中使用此元素时,当用户出现验证错误(即模型验证)时,它会重定向到登录/注册操作页面(而不是更新元素).

I have my login and registration forms in elements that reference the users controller and login() and register() actions. When I use this element in a modal or on a page controller action, for example, it redirects to the login/registration action page (rather than update the element), when the user has validation errors (model validation, that is).

我意识到我可以使用 Javascript/JQuery 验证,但是有什么方法可以让 CakePHP 的模型验证更新元素而不是在发生错误时重定向到原始操作的页面?

I realize that I could use Javascript/JQuery validation, but is there any way to have CakePHP's model validation update the element rather than redirect to the original action's page when errors occur?

推荐答案

我过去曾用 这个 PersistentValidation 组件.您设置它的方法是将 PersistentValidation 组件包含在您的 UsersController 以及您计划包含登录/注册元素的任何其他控制器中.

I've solved this issue in the past with this PersistentValidation component. The way you set it up is by including the PersistentValidation component in your UsersController, and any other controller where you're planning to include the login/register elements.

您的登录/注册表格将提交给他们各自的控制器操作.如果验证失败,该操作将重定向回引用页面.例如:

Your login/registration forms would submit to their respective controller actions. If validation fails, the action would redirect back to the referring page. For example:

if (!$validated) {
    $this->redirect($this->referer());
}

由您重定向到的操作调用的视图将自动填充上一个请求中的验证错误.

The view invoked by the action to which you redirect will be automagically seeded with the validation errors from the previous request.

这在幕后工作,通过将验证错误存储在会话变量中,并在重定向后检索这些错误,使它们可用于当前请求的视图/元素.您可以自己执行此操作,但该组件使用起来非常轻松.

This works, behind-the-scenes, by storing the validation errors in a session variable, and retrieving these errors after the redirect, making them available for the current request's views/elements. You could do this yourself, but the component makes it very painless to use.

相关文章