2012-06-14 128 views
0

我有一個CakePHP的2.1驗證規則模型驗證規則和功能

'name' => array(

       'empty' => array(
        'rule' => 'notEmpty', 
        'required' => true, 
        'allowEmpty' => false, 
        'message' => 'Name is required.' 
       ), 
       'unique' => array(
       'rule' => 'checkUnique', 
       'required' => true, 
       'allowEmpty' => false, 
       'message' => 'Name already exists.' 
       ) 
      ) 

我爲TE checkUnique方法如下代碼:

public function checkUnique($data) 
    { 
//App::import('Model','User'); 
// $this->User = & new User(); 


if(empty($this->data['TeacherLocation']['id'])) 
{ 
    $locationInfo = $this->find 
    (
     'all', 
     array 
     (
      'conditions'=>array 
      (
       'user_id' => $this->data['TeacherLocation']['user_id'], 
       'name' => $this->data['TeacherLocation']['name'] 
      ), 
      'recursive' => -1 
     ) 
    ); 

    return (empty($locationInfo)); 

但我不斷收到關於無法一個錯誤找到索引user_id。是什麼賦予了?

回答

0

所以基本上你想檢查isUnique基於額外的領域,對不對?

試試我的方法validateUnique: https://github.com/dereuromark/tools/blob/2.0/Lib/MyModel.php#L818

所以你有:

 'name' => array(
     ... 
     'unique' => array(
      'rule' => array('validateUnique', array('user_id')), 
      'required' => true, 
      'allowEmpty' => false, 
      'message' => 'Name already exists.' 
     ) 
    ) 

您的問題似乎是,即使是在你傳遞的數據沒有USER_ID您的驗證方法被觸發。

0

isUnique設置已經內置到蛋糕:

'name' => array(
    'isUnique' => array(
     'rule' => array('isUnique'), 
     'message' => 'Name already exists', 
    ),