【发布时间】:2012-11-24 15:12:43
【问题描述】:
我正在尝试在 saveAll 上验证多个模型。第一个模型中的验证正在被触发,但是当涉及到相关模型时,似乎什么都没有发生。我什至尝试通过退出来检查 beforeValidate() 和 beforeSave() 方法是否被调用;在它们中,但代码继续正常执行。
ContactDetails 模型:
<?php
class ContactDetails extends ContactAppModel {
public $actsAs = array("MapValidate");
public $hasMany = array(
'ProjectLocation' => array(
'className' => 'ProjectLocation',
'foreignKey' => 'project_id'
)
);
public $validate = array(
'name' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Contact name is required'
)
),
'address1' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Contact address 1 is required'
)
),
'email' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Contact email is required'
),
'email' => array(
'rule' => array('email'),
'message' => 'Contact email format is not valid'
)
)
);
}
项目位置模型:
<?php
class ProjectLocation extends ContactAppModel {
public $actsAs = array("MapValidate");
public $belongsTo = array(
"ContactDetails" => array(
"className" => "ContactDetails",
"foreignKey" => "project_id"
);
);
public $validate = array(
'lat' => array(
'checkLocation' => array(
'rule' => array('checkMap', 'lat'),
'message' => 'One or more positions on the map are invalid.'
)
)
);
}
这是我要保存的 $this->request->数据:
Array
(
[ContactDetails] => Array
(
[id] => 1
[name] => PreeoStudios
[address1] => 4, Stivala Street
[address2] => Mosta, MST 3205
[address3] => Malta
[telephone] => 34562737
[email] => info@preeostudios.com
[fax] => N/A
[skype] => N/A
)
[ProjectLocation] => Array
(
[0] => Array
(
[lat] => 35.886277456343024
[lon] => 14.428907312499973
)
[1] => Array
(
[lat] => 35.886277456343024
[lon] => 14.528907312499973
)
)
)
saveAll 调用:
$this->ContactDetails->saveAll($this->request->data, array('validate' => 'first'))
编辑
我还尝试从关联模型中删除验证规则,并在 beforeSave 函数中退出...代码只是继续执行
<?php
class ProjectLocation extends ContactAppModel {
public $actsAs = array("MapValidate");
public $belongsTo = array(
"ContactDetails" => array(
"className" => "ContactDetails",
"foreignKey" => "project_id"
);
);
public function beforeSave(){
exit;
}
public $validate = array(
);
}
【问题讨论】:
-
您能否也发布您定义的
checkMap验证方法的代码?您也可以尝试使用saveAssociated()进行测试。另外,为什么要将字符串“lat”传递给验证? -
我会尝试为 ProjectLocation 保存一行,看看它是否得到验证。就像 Borislav Sabev 所说,您不需要将字段名称传递给自定义验证规则。有点奇怪,但是字段名默认是第一个参数传入的,后面是验证函数名后面指定的其他参数。
-
我试着按照你告诉我的去做,但仍然没有成功:/我用我尝试的一些改变更新了这个问题。
标签: cakephp cakephp-2.2