第一个问题是我的表中有以下验证器和公共函数
- 用户表.php*
$validator
->scalar('name')
->maxLength('name', 45)
->requirePresence('name', 'create')
->notEmptyString('name', 'You must enter a name for the user.');
$validator
->add('name', 'custom', array('rule' => 'checkExistingUser', 'message' => 'This user already appears to be in the system.', 'on' => 'create'));
public function checkExistingUser($value,$context)
{
return $this->find('all', ['conditions' => ['Users.name' => $context['data']['name'], 'Users.user_type_id' => $context['data']['user_type_id']]])->count() < 1 ;
}
保存下面的表单时,收到消息“Method checkExistingUser does not exist”。为什么它无法识别表模型中明确定义的方法?我是否遗漏了什么?
- 添加.ctp*
<?php echo $this->Form->create($user);?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php
echo $this->Form->control('name', ['type' => 'text']);
echo $this->Form->control('user_type_id');
echo $this->Form->control('owner', array('type' => 'text', 'label' => "Owner Name"));
echo $this->Form->control('owner_contact', array('type' => 'text', 'label' => "Owner Contact (phone, email etc)"));
echo $this->Form->control('description', ['type' => 'textarea']);
echo $this->Form->control('ia_exception', array('type' => 'text', 'label' => "IA Exception Number"));
echo $this->Form->control('is_manual', array('type' => 'checkbox', 'label' => "Password Updated Manually"));
echo $this->Form->control('Environment', ['type' => 'select', 'multiple' => 'true', 'label' => 'Environment(s)']);
?>
</fieldset>
<div class="buttons">
<?php
echo $this->Form->button('Save', ['type'=> 'submit', 'name' => 'submit']);
echo $this->Form->button('Cancel', ['type' => 'button', 'name'=>'cancel', 'onClick' => 'history.go(-1);return true;']);
echo $this->Form->end();
?>
</div>
- 用户控制器.php*
function add() {
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->set('The user has been saved');
return $this->redirect(array('action' => 'index'));
} else {
$this->Flash->set('The user could not be saved. Please, try again.');
}
}
$userTypes = $this->Users->UserTypes->find('list');
$changeSteps = $this->Users->ChangeSteps->find('list');
$environments = $this->Users->Environments->find('list');
$this->set(compact('user','userTypes', 'changeSteps', 'environments'));
}
第二个问题是,当我尝试送出表单以检查验证程式是否能正确行程空白的 name 字段时,我没有收到“您必须输入使用者的名称”消息,而是收到“这个字段是必要的”消息。为何它没有显示我来自notEmptyString的消息?“这个字段是必要的”是从哪里来的?
2条答案
按热度按时间ycggw6v21#
对于第一个问题,我必须在我的验证器中添加一个提供者。
我变了
到这
aydmsdu92#
在打补丁的过程中,要小心使用自定义的验证方法,因为Cake期望返回字符串,否则它将呈现默认的消息。
同样适用于密封件。
这将返回默认的消息而不是自定义的消息(“至少..”),因为我们设置了一个可调用的not-cakephp函数作为自定义验证的规则,所以消息应该由被调用的函数返回: