2012-12-01 14 views
1

我需要Cakephp 2.2專家來幫助我。 我想進行更新,用下面的「$這個 - >數據」:Cakephp驗證規則在更新時觸發,即使在on =>'create'指定

array(
    'Button' => array(
     (int) 0 => array(
      'id' => '1', 
      'on' => '0' 
     ), 
     (int) 1 => array(
      'id' => '2', 
      'on' => '0' 
     ), 
     (int) 2 => array(
      'id' => '3', 
      'on' => '1' 
     ), 
     (int) 3 => array(
      'id' => '4', 
      'on' => '1' 
     ) 
    ) 
) 

按鈕模型中的驗證規則是:

public $validate = array(
     'id'=>array(
      'notEmpty'  => array(
       'rule'  => 'notEmpty', 
       'required' => true, 
       'message' => 'Module id can not be empty', 
       'on'  => 'update' 
      ),  
      'naturalNumber' => array(
       'rule'  => 'naturalNumber' , 
       'message' => 'Module id is not integer', 
       'on'  => 'update' 
      ) 
     ),  
     'name'=>array(
      'notEmpty'  => array(
       'rule'  => 'notEmpty', 
       'required' => true, 
       'message' => 'Module name can not be empty', 
       'on'  => 'create'     
      ),  
      'alphaNumericWithSpaces' => array(
       'rule'  => array('custom', '/^[a-z0-9 ]*$/i') , 
       'message' => 'Module category is not alphanumeric' 
      ) 
     ), 
     'type'=>array(
      'notEmpty'  => array(
       'rule'  => 'notEmpty', 
       'required' => true, 
       'message' => 'Module category can not be empty', 
       'on'  => 'create' 
      ), 
      'naturalNumber' => array(
       'rule'  => 'naturalNumber', 
       'message' => 'Module category is not integer' 
      ) 
     ), 
     'on'=>array(
      'boolean'  => array(
       'rule'  => 'boolean', 
       'message' => 'Module ON value is not boolean' 
      ) 
     )); 

,然後,在控制器中,我有下面的代碼:

if(!empty($this->data)) { 
    if($this->Button->saveAll($this->data)) { 
    debug ('Saved!'); 
    } 
    else { 
    debug($this->Button->validationErrors); 
    } 
} 

的問題是,「白水()」未作出更新,並觸發以下驗證錯誤,即使我已經對=>「創建」用在這些領域火僅在創建記錄時:

array(
    'name' => array(
     (int) 0 => 'Module name can not be empty' 
    ), 
    'type' => array(
     (int) 0 => 'Module category can not be empty' 
    ) 
) 

謝謝!

回答

1

爲了使saveAll的機制不會阻礙,請嘗試使用save()和單個記錄。在CakePHP 2.2.4中,CakeValidationSet :: validate()在查看'required'之前,一定要檢查'on'(通過$ rule-> skip())。錯誤表明它正在嘗試創建,而不是更新。

要保存許多Button記錄,您可能需要嘗試使用$ data結構。也許還可以使用saveMany()以及

array(
    (int) 0 => array( 
     'Button' => array(
      'id' => '1', 
      'on' => '0' 
     ) 
    ) 
    (int) 1 => array(
     'Button' => array(
      'id' => '2', 
      'on' => '0' 
     ) 
    ), 
    (int) 2 => array(
     'Button' => array(
      'id' => '3', 
      'on' => '1' 
     ) 
    ), 
    (int) 3 => array(
     'Button' => array(
      'id' => '4', 
      'on' => '1' 
     ) 
    ) 
)