2012-03-12 51 views
2

我的表單包含一個模型對象,它包含使用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; 
    } 
} 

?> 

回答

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); 
    } 
} 
?> 

+0

感謝您的快速響應對不起,我認爲我的問題有點不清楚,我沒有試圖驗證信息,我試圖做的是「如果與ModelA有關的字段是空的,在數據庫中添加一行「我不想要求用戶填寫這些字段,這些將是可選字段,如果填寫,應該保存,否則,他們不應該是。 – 2012-03-12 17:48:21

+0

你不能使用cakephp創建一個事務,所以如果任何數據產生問題,你創建一個回滾 – Lefsler 2012-03-13 18:22:51

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