首页 > 解决方案 > 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 中那样在表单(或任何地方)中的字段上显示它。

我还需要做什么?

标签: cakephpcakephp-4.x

解决方案


感谢Salines,我使用了

echo $this->Form->create($user);

代替

echo $this->Form->create();

并立即出现错误。


推荐阅读