cakephp - CakePHP 4.0 - 如何创建和显示针对字段的验证错误?
问题描述
我正在使用 CakePHP 4.0,并创建一个用户注册页面。我已经设置了一些验证规则,它们会在预期的时候返回错误,但我不知道如何让它们显示在表单中的适当字段上。在 v3.0 中,这似乎是自动发生的。
我的表格(in register.php
)是:
echo $this->Flash->render();
echo $this->Form->create();
echo $this->Form->control('name');
echo $this->Form->control('email');
echo $this->Form->control('password', array('type' => 'password'));
echo $this->Form->control('confirm_password', array('type' => 'password'));
在UsersController.php
我有行动register
:
public function register() {
$user = $this->Users->newEmptyEntity();
if($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->getData());
if($user->getErrors()) {
$this->Flash->error(__('Unable to register you. Please make sure you have completed all fields correctly.'));
}else {
$this->Users->save($user);
$this->Flash->success(__('Success'));
return redirect($this->get_home());
}
}
$this->set('user', $user);
}
UsersTable 中的验证规则是:
public function validationDefault(Validator $validator): Validator {
$validator->requirePresence([
'name' => [
'mode' => 'create',
'message' => 'Please enter your name'
],
'email' => [
'mode' => true,
'message' => 'Please enter your email address'
]
])
->allowEmptyString('name', 'Name cannot be empty', false);
}
如果我提交表单时没有输入任何名称或电子邮件地址,getErrors() 会选取无效字段并创建一个数组,我可以通过调试看到该数组包含:
'name' => [
'_empty' => 'Name cannot be empty'
]
所以它已经意识到 name 字段没有验证,但它没有像在版本 3.0 中那样在表单(或任何地方)中的字段上显示它。
我还需要做什么?
解决方案
感谢Salines,我使用了
echo $this->Form->create($user);
代替
echo $this->Form->create();
并立即出现错误。
推荐阅读
- php - 如何使用 ajax 和 php 在模态按钮中添加动作
- objective-c - Objective-C NSMutableAttributedString text4 字体没有显示正确的字体
- javascript - 确认下拉菜单中的特殊值
- database - 如何设计数据库以存储“默认”项目
- mysql - 在同一引用中从同一列中查找两个值
- reactjs - 尝试运行 React 教程代码时渲染()中的神秘错误
- django - 用户不会验证 Django
- javascript - 从 setInterval 回调调用时,如何确保在弹出“警报”之前呈现 HTML 内容?
- python - Django 2 -403 禁止错误:无法从views.py 发出获取请求
- linux - 如何使用 python 在后台运行 ssh 反向隧道?