我正在尝试在我的模型UsersTable中使用validationDefault方法:
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class UsersTable extends Table
{
public function initialize(array $config)
{
$this->addBehavior('Timestamp');
$this->setTable('users');
$this->setPrimaryKey('id');
}
public function validationDefault(Validator $validator)
{
$validator->add('login', [
'length' => [
'rule' => ['minLength',3],
'message' => __('Login need to be at least 3 characters long')
]
]);
return $validator;
}
}
在我的用户控制器中,我有以下代码:
<?php
namespace App\Controller;
use Cake\Validation\Validator;
class UsersController extends AppController {
public function initialize() {
parent::initialize();
}
public function add() {
if ($this->request->is('post')) {
$user = $this->Users->newEntity($this->request->getData());
if ($this->Users->save($user)) {
$this->Flash->success(__('Your user has been created.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to create your user.'));
}
我的表单如下:
<?= $this->Form->create('Users', ['url' => ['controller' => 'Users', 'action' => 'add']]); ?>
<fieldset>
<legend><?= __('Ajouter un utilisateur') ?></legend>
<?= $this->Form->control('login') ?>
<?= $this->Form->control('password') ?>
<?= $this->Form->control('role', [
'options' => ['admin' => 'Admin', 'author' => 'Author']
]) ?>
</fieldset>
<?= $this->Form->button(__('Ajouter')); ?>
<?= $this->Form->end() ?>
如果我在登录表单中使用带有“aa”的表单,则会在数据库中插入数据。但它们不应该插入,因为验证器将minLength定义为3。
当我使用save方法时,似乎不会调用validationDefault。
这是var $ user的调试:
object(Cake\ORM\Entity) {
'login' => 'g',
'password' => '',
'role' => 'admin',
'[new]' => true,
'[accessible]' => [
'*' => true
],
'[dirty]' => [
'login' => true,
'password' => true,
'role' => true
],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'Users'
}
注意:如果我在控制器中直接使用验证器,则会出现错误:登录需要至少3个字符。但我不想在控制器中直接使用验证器... < / p>
$validator = new Validator();
$validator->add('login', [
'length' => ['rule' => ['minLength', 3],
'message' => __('Login need to be at least 3 characters long')
]
]);
if($validator->errors($this->request->getData())) {
debug($validator->errors($this->request->getData()));
}
答案 0 :(得分:0)
我问这个问题是在IRC上引导#cakephp,他们告诉我重新安装cakephp但是使用bake来生成模型类。
之后,一切正常。