【发布时间】:2018-05-23 20:32:16
【问题描述】:
我在使用自定义验证器显示表单的验证错误时遇到问题。 调试方法显示的错误确实存在,只是不会显示在表单中。
我希望能够在该字段下方(或上方,或任何地方)显示错误消息。
我尝试过的
好吧,documentation 确实说明了:
当使用 View\Helper\FormHelper::control() 时,错误由 默认,所以你不需要使用 isFieldError() 或调用 error() 手动。
尽管如此,我在表单中添加了以下内容(就在电子邮件控件下方),但并没有做更多的事情。没有消息显示。
if ($this->Form->isFieldError('email')) {
echo $this->Form->error('email', 'Yes, it fails!');
}
我还在 SO 上找到了几个关于这个问题的问题和答案,但它们看起来已经过时(从 '09 到 '13)并且似乎不符合今天的 CakePHP 语法。
我做了什么
用户/forgot_password.ctp
<?= $this->Form->create() ?>
<?= $this->Form->control('email', ['type' => 'email']) ?>
<?= $this->Form->button(__('Reset my password')) ?>
<?= $this->Form->end() ?>
UsersController.php
(注意具体的验证集,如documentation中所述)
public function forgotPassword()
{
if ($this->request->is('post')) {
$user = $this->Users->newEntity($this->request->getData(), ['validate' => 'email']);
if ($user->errors()) {
debug($user->errors()); // <- shows the validation error
$this->Flash->error(__('An error occurred.'));
} else {
// ... procedure to reset password (which works fine!) and redirect to login...
return $this->redirect(['action' => 'login']);
}
}
}
UsersTable.php
public function validationEmail(Validator $validator)
{
$validator
->email('email')
->notEmpty('email', __('An email address is required.'));
return $validator;
}
它是什么样子的
更新
感谢@ndm 评论,这是显示错误的正确方法。
在UsersController.php:
public function forgotPassword()
{
// user context for the form
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity(§user, $this->request->getData(), ['validate' => 'email']); <- validation done on patchEntity
if ($user->errors()) {
$this->Flash->error(__('An error occurred.'));
} else {
// ... procedure to reset password and redirect to login...
return $this->redirect(['action' => 'login']);
}
}
// pass context to view
$this->set(compact('user'));
}
在视图中forgotPassword.ctp:
<?= $this->Form->create($user) ?>
【问题讨论】:
-
@ndm 谢谢!我还没有看到解决我问题的答案。我确实错过了上下文。现在一切都清楚了。
标签: php validation cakephp-3.x