我在使用自定义验证程序显示表单的验证错误时遇到问题。 调试方法显示错误确实存在,它不会显示在表单中。
我希望能够在该字段下(或上方或任何位置)显示错误消息。
嗯,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) ?>
答案 0 :(得分:-1)
//modify your function as below
public function forgotPassword()
{
if ($this->request->is('post')) {
$user = $this->Users->newEntity($this->request->getData(), ['validate' => 'email']);
if ($user->getErrors()) {
debug($user->getError('email')); // <- shows the validation error
$this->Flash->error(__($user->getError('email')['_empty']));
} else {
// ... procedure to reset password (which works fine!) and redirect to login...
return $this->redirect(['action' => 'login']);
}
}
}