2016-01-11 56 views
-2

我有一個HABTM關係,如:Post <-> Tag(一個Post可以有多個標記,而其他方式相同)。使用CakePHP 2.x HABTM表單驗證

這項工作由Cakephp生成的多個複選框選擇。但是我希望每個帖子都至少有一個Tag,並且如果有人試圖插入一個孤兒,就會拋出一個錯誤。

我正在尋找最乾淨/最CakePHP的方式來做到這一點。


這是或多或少這個HABTM form validation in CakePHP問題的更新,因爲我得到了同樣的問題在我的CakePHP的2.7(去年CakePHP的2.x的,現在用PHP 5.3支持在2016年的數據)和可以」找到一個好方法來做到這一點。

回答

0

下面是我認爲現在最好的。它使用cakephp 3.x行爲進行HABTM驗證。

我選擇只在模型中使用最普通的代碼。

在你AppModel.php,設置此beforeValidate()afterValidate()

class AppModel extends Model { 
    /** @var array set the behaviour to `Containable` */ 
public $actsAs = array('Containable'); 

    /** 
    * copy the HABTM post value in the data validation scope 
    * from data[distantModel][distantModel] to data[model][distantModel] 
    * @return bool true 
    */ 
public function beforeValidate($options = array()){ 
    foreach (array_keys($this->hasAndBelongsToMany) as $model){ 
    if(isset($this->data[$model][$model])) 
     $this->data[$this->name][$model] = $this->data[$model][$model]; 
    } 

    return true; 
} 

    /** 
    * delete the HABTM value of the data validation scope (undo beforeValidate()) 
    * and add the error returned by main model in the distant HABTM model scope 
    * @return bool true 
    */ 
public function afterValidate($options = array()){ 
    foreach (array_keys($this->hasAndBelongsToMany) as $model){ 
    unset($this->data[$this->name][$model]); 
    if(isset($this->validationErrors[$model])) 
     $this->$model->validationErrors[$model] = $this->validationErrors[$model]; 
    } 

    return true; 
} 
} 

在此之後,您可以使用您的驗證在你的模型是這樣的:

class Post extends AppModel { 

    public $validate = array(
     // [...] 
     'Tag' => array(
       // here we ask for min 1 tag 
      'rule' => array('multiple', array('min' => 1)), 
      'required' => true, 
      'message' => 'Please select at least one Tag for this Post.' 
      ) 
     ); 

     /** @var array many Post belong to many Tag */ 
    public $hasAndBelongsToMany = array(
     'Tag' => array(
      // [...] 
      ) 
     ); 
} 

這個答案用途: