Cakephp - 有条件保存
问题描述:
我的表单包含一个模型对象,它包含使用hasMany相关的五个子对象。当我保存表单时,我注意到所有字段(无论它们是否为空)都被保存到数据库中。是否可以在beforeSave()回调方法中设置一个条件来防止没有值的子项保存?我试图取消包含空值的数组中的键,但该行仍被添加到数据库中。Cakephp - 有条件保存
这里是我的'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;
}
}
?>
答
你有没有尝试过这样的:在你的模型
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);
}
}
?>
答
我已经使用这个代码:
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;
}
你提到你尝试过这已经发布您的代码在你原来的职位
?+0
我发布了我的代码。我正在检查复选框的值。如果没有选中,那么我想取消设置该部分所具有的字段的值。但是,尽管我没有设置,但是添加的行只包含Mtd表的外键。 – 2012-03-12 18:37:44
感谢您的快速响应对不起,我认为我的问题有点不清楚,我没有试图验证信息,我试图做的是“如果与ModelA有关的字段是空的,在数据库中添加一行“我不想要求用户填写这些字段,这些将是可选字段,如果填写,应该保存,否则,他们不应该是。 – 2012-03-12 17:48:21
你不能使用cakephp创建一个事务,所以如果任何数据产生问题,你创建一个回滚 – Lefsler 2012-03-13 18:22:51