-1

私は次のようなHABTM関係を持っています:(Post <-> Tag投稿には複数のタグを付けることができ、他の方法も同じです)。

これは、Cakephp によって生成された複数のチェックボックス選択で機能します。しかし、投稿ごとに少なくとも 1 つのタグを設定し、誰かが孤立したタグを挿入しようとするとエラーをスローしたいと考えています。

これを行うための最もクリーンで最も CakePHP に似た方法を探しています。


これは多かれ少なかれ、このHABTM form validation in CakePHPの質問の更新です。私の cakephp 2.7 (2016 年の日付で php 5.3 をサポートする最後の cakephp 2.x) で同じ問題が発生し、それを行う良い方法。

4

1 に答える 1

1

今のところベストだと思うのはこちら。HABTM 検証に Cakephp 3.x の動作を使用します。

最も一般的なコードを使用して、モデルでのみ作業することを選択します。

で、これを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(
            // [...]
            )
        );
}

この回答の使用:

于 2016-01-11T13:57:48.187 に答える