在 Cakephp3.3 中验证不是“添加”或“编辑”的表单

Validating a form that is not ‘add’ or ‘edit’ in Cakephp3.3

我正在学习 Cakephp3.3,并且 运行 在保存之前尝试验证表单时遇到了问题。

我在“src/Template/Users”中创建了一个名为“register.ctp”的新表单,并在“src/Controller/UsersController”中添加了一个名为“register”的操作。

我想在保存之前验证表单提交,但不知道如何进行。

FWIW,预保存验证非常适合“添加”和“编辑”表单,尽管我认为这在 Cakephp3 中默认发生。

有没有办法让这些相同的验证规则适用于“注册”表单?

仅供参考,'register' 操作实际上是更新以前为匿名用户创建的现有用户记录。

控制器动作如下:

<?php
namespace App\Controller;

use App\Controller\AppController;
use Cake\Event\Event;

class UsersController extends AppController
{

//<snipped methods>

public function register()
{
    if($this->request->session()->read('Auth.User'))
    {
        $id = $this->request->session()->read('Auth.User.id');
        if ($this->request->is(['patch', 'post', 'put'])) 
        {
            $user = $this->Users->get($id, [
                'contain' => []
            ]);
            $user = $this->Users->patchEntity($user, $this->request->data);

            if ($this->Users->save($user)) 
            {
                $this->Flash->success(__('Your free trial period has started.'));
                return $this->redirect("/Home/index");
            } 
            else 
            {
                $this->Flash->error(__('We were unable to start your trial. Please, try again.'));
            }
        }
    } 
    else 
    {
        $this->Flash->error(__('Your demo session has expired. Please start again.'));
    }

    $this->set(compact('user'));
    $this->set('_serialize', ['user']);
}
}

这是具有验证规则的 UsersTable 模型:

<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

class UsersTable extends Table
{

public function initialize(array $config)
{
    parent::initialize($config);

    $this->table('users');
    $this->displayField('id');
    $this->primaryKey('id');

    $this->addBehavior('Timestamp');

}

public function validationDefault(Validator $validator)
{
    $validator
        ->integer('id')
        ->allowEmpty('id', 'create');

    $validator
        ->email('email')
        ->requirePresence('email')
        ->notEmpty('An email address is required.');

    $validator
        ->requirePresence('password')
        ->notEmpty('A password is required.');

    $validator
        ->requirePresence('firstname')
        ->notEmpty('firstname')
        ->add('firstname', 'minlength',['rule' => ['minlength', 1]]);

    $validator
        ->requirePresence('lastname')
        ->notEmpty('lastname')
        ->add('lastname', 'minlength',['rule' => ['minlength', 1]]);

    $validator
        ->integer('status')
        ->requirePresence('status', 'create')
        ->notEmpty('status');

    $validator
        ->add('role', 'inList', [
            'rule' => ['inlist', ['admin','author','subscriber']],
            'message' => 'Please enter a valid role.'
            ]);

    $validator
        ->requirePresence('referer', 'create')
        ->allowEmpty('referer');

    $validator
        ->integer('plan_id')
        ->requirePresence('plan_id', 'create')
        ->notEmpty('plan_id');

    return $validator;
}

public function buildRules(RulesChecker $rules)
{
    $rules->add($rules->isUnique(['email']));
    return $rules;
}
}

这是 register.ctp 表格:

<div class="users form large-12 columns ">
    <?= $this->Form->create() ?>
        <fieldset>
            <legend><?= __('Sign Up For Your No-Risk Free Trial!') ?></legend>
            <?= $this->Form->input('firstname'); ?>
            <?= $this->Form->input('lastname'); ?>
            <?= $this->Form->input('email'); ?>
            <?= $this->Form->input('password'); ?>
        </fieldset>
        <?= $this->Form->button(__('Start My Free Trial Now')) ?>
    <?= $this->Form->end() ?>
</div>

如有任何帮助,我们将不胜感激!

如果您想保存,则将应用默认验证规则。如果您不想应用默认规则,则只需添加 'validate' => false 参数

$user = $this->Users->patchEntity($user, $this->request->data,['validate' => false])

如果您只想为注册选项自定义验证规则,则需要在 TABLE

中创建新函数
class UsersTable extends Table
{
    public function validationRegister($validator)
    {
        $validator
        ->email('email')
        ->requirePresence('email')
        ->notEmpty('An email address is required.');

    $validator
        ->requirePresence('password')
        ->notEmpty('A password is required.');

    $validator
        ->requirePresence('firstname')
        ->notEmpty('firstname')
        ->add('firstname', 'minlength',['rule' => ['minlength', 1]]);

    return $validator;
    }
}

现在在控制器 newEntity 或 patchEntity 函数中设置 'validate' => 'register' 参数

$user = $this->Users->patchEntity($user, $this->request->data,['validate' => 'register'])