HABTM form validation in CakePHP

前端 未结 7 1369
我在风中等你
我在风中等你 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 07:04

    Try this:

    // app/models/project.php
    /**
     * An additional validation check to ensure at least one User is
     * selected. Spoofs Cake into thinking that there are validation
     * errors on the Project model by invalidating a non-existent field
     * on the Project model, then also invalidates the habtm field as
     * well, so when the form is re-displayed, the error is displayed
     * on the User field.
     **/
    function beforeValidate() {
      if (!isset($this->data['User']['User'])
      || empty($this->data['User']['User'])) {
        $this->invalidate('non_existent_field'); // fake validation error on Project
        $this->User->invalidate('User', 'Please select at least one user');
      }
      return true;
    }
    

提交回复
热议问题