我有一个项目表和一个用户表,它们通过 HABTM 关系链接。在“添加”新项目页面中,我有一个多个复选框部分,用于为新项目选择用户。我希望该项目至少有一名用户。在 CakePHP 中解决这个问题的最佳方法是什么?

请您参考如下方法:

尝试这个:

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


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!