HABTM form validation in CakePHP

前端 未结 7 1377
我在风中等你
我在风中等你 2020-12-03 06:33

I have a Projects table and a Users table which are linked by a HABTM relation. In the \"add\" new Project page I have a multiple checkbox section to select Users for the ne

7条回答
  •  天命终不由人
    2020-12-03 06:49

    2016 update for CakePhp 2.7

    Full answer here : HABTM form validation with CakePHP 2.x


    TL;DR;

    AppModel.php

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

    In the main model of your HABTM :

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

提交回复
热议问题