我在同一页面上有两个模型:
-
人需要(总是)
-
用户(可选)
人员字段id|firstname|lastname|gender
用户字段:id|username|password|password_confirm
这些字段有notEmpty验证规则,password和password_confirm有自定义验证规则(matchpassword)。
如果我不填充视图中的任何User字段,空模型表示有效。但如果任何字段不为空,则用户验证规则将正常工作。
所以在以下情况下保存:
- Person所有字段都已填充,所有User字段为空
或
- Person all如果字段已填满,User字段也已填满
其他情况我想知道为什么我不能保存
的确切原因主要任务是添加函数,但是我现在完全困惑了,不知道怎么做。
Update1 :对不起,我犯了一个错误,验证规则不是为两个模型空
Update2:i was try check User validation before save
public function add() {
unset($this->Group->User->validate['username']);//i switched off the notempty rule here
if ($this->request->is('post')) {
$this->Group->create();
if ($this->Group->save($this->request->data))
{
$this->Session->setFlash(__('The group has been saved.'));
//try to check validation before saving
$this->Group->User->set( $this->data );
if ($this->Group->User->validates()) {
//group saved ok, now add people
$group_id=$this->Group->getInsertId();
if(!empty($this->request->data['User']))
foreach($this->request->data['User'] as $user) {
//loop for each person added
$user['group_id']=$group_id;
$this->Group->User->create();
if($this->Group->User->save($user))
{
debug($this->Group->User->validates());
$this->Session->setFlash(__('The Userhas been saved.'));}
}//end foreach
return $this->redirect(array('action' => 'index'));
}else{
$this->Session->setFlash(__('The User could not been saved.'));
}
}
else {
$this->Session->setFlash(__('The group could not be saved. Please, try again.'));
}
}
}
有以下错误:即使用户名字段为空,即使使用group_id保存的字段完全为空,其他字段为空,也会保存用户。
Update3: 我实现了cwbit第二个解决方案(也修改了行为以与2.x兼容),但这对我不起作用
public $validate = array(
'password'=>array('username'=>array(
'rule'=>'notEmpty',
'if'=>array('username')//if the username exist, the password is notEmpty if i good understand
)
);
您可以在使用Hash::filter()
保存/验证之前检查$this->request->data['User']
是否为空(参见文档中的哈希实用程序):-
if (empty(Hash::filter($this->request->data['User']))) {
unset($this->request->data['User'])
}
首先,您需要确保在适当的模型中保持验证规则—即Person
应该不知道User
内部发生了什么,反之亦然。这是因为你的应用程序是模块化的,可扩展的,并保持它的完整性每个模型应该是自己的数据的最终权威
选项1:首先检查控制器中的数据
也就是说,您可以在控制器中选择应该保存的数据-因此,就像@drmonkeyninja所说的那样,您可以轻松检查$this->data['User']
中是否设置了任何内容,如果没有,则从保存的数据中删除它。这可能是你最好的选择,因为控制器/视图组合以这样一种方式暴露表单,特殊的数据组合是可能的。
选项2:条件验证
如果你想要一些不同的东西,你可以使用像ConditionalValidation Behavior这样的东西,只在满足某些先决条件时运行某些验证规则
- 只运行规则XYZ如果字段ABC存在并且== true
- 只运行规则XYZ,如果字段ABC存在,为真,字段DEF存在并且>= 123
- 等。
在蛋糕1中有一个行为。x应该很容易适应蛋糕2。X(只需要更改文件名)
- https://github.com/cwbit/cakephp-conditionalvalidation