我的表单包含一个模型对象,其中包含五个使用hasMany相关的子对象。当我保存表单时,我注意到所有字段,无论它们是否为空,都会保存到数据库中。是否可以在beforeSave()回调方法中设置条件以防止没有值的子项被保存?我试图取消设置包含空值的数组中的键,但该行仍在添加到数据库中。
这是我的'Mtd'模型的代码。 Mtd模型包含许多Flowratereatments。在我的表格上,我有一个复选框,上面写着“这是基于流量的治疗”。因此,如果用户点击它,则用户可以在字段中填写它。但是,如果用户没有填写它,我想防止仅使用Mtd表的外键添加新行。
<?php
class Mtd extends AppModel {
public $name = 'Mtd';
public $hasOne = array('Treatmentdesign', 'Volumetreatment');
public $hasMany = 'Flowratetreatment';
function beforeSave() {
if($this->data['Mtd']['is_settling'] != 1){
unset($this->data['Flowratetreatment'][0]);
}
return true;
}
}
?>
答案 0 :(得分:0)
你有没有试过像:
class User extends AppModel {
function validates() {
$this->setAction();
#always validate presence of username
$this->validates_presence_of('username');
#validate uniqueness of username when creating a new user
$this->validates_uniqueness_of('username',array('on'=>'create'));
#validate length of username (minimum)
$this->validates_length_of('username',array('min'=>3));
#validate length of username (maximum)
$this->validates_length_of('username',array('max'=>50));
#validate presence of password
$this->validates_presence_of('password');
#validate presence of email
$this->validates_presence_of('email');
#validate uniqueness of email when creating a new user
$this->validates_uniqueness_of('email',array('on'=>'create'));
#validate format of email
$this->validates_format_of('email',VALID_EMAIL);
#if there were errors, return false
$errors = $this->invalidFields();
return (count($errors) == 0);
}
}
?>
在您的模型中
答案 1 :(得分:0)
我使用过这段代码:
public function beforeSave() {
if(isset($this->data[$this->alias]['profile_picture'])) {
if($this->data[$this->alias]['profile_picture']['error']==4) {
unset($this->data[$this->alias]['profile_picture']);
}
}
return true;
}
在之前的应用中,如果用户尚未上传文件,则从$this->data
删除密钥,以防止旧值被覆盖。
这应该适合您(您需要根据$this->data
包含的内容进行调整。
public function beforeSave() {
if(empty($this->data[$this->alias]['the_key'])) {
unset($this->data[$this->alias]['the_key']);
}
//debug($this->data); exit; // this is what will be saved
return true;
}
你提到你试过这个吗?将您的代码发布在原始帖子中。