2012-08-26 39 views
0

我在CakePHP中的表單有一個奇怪的問題。我有一系列以複選框開頭的問題。如果選中該複選框,我想要另外輸入兩個字段。否則,如果未選中,它們是可選的。我寫了一個用於驗證輸入字段的自定義函數。這裏是其中之一:複選框上的CakePHP自定義表單驗證

public function rn_number() { 
if ($this->data['Education']['rn_box'] == 1) { 
    if($this->data['Education']['rn_number'] == '') 
     return false 
} 

return true; 
} 

public $validate = array(
    'rn_number' => array(
      'rn_number'=>array(
       'rule' => 'rn_number' 
       ), 
      ), 
); 

驗證工作正常。對於上述規則,它會檢查ID爲'cna_box'的複選框是否值爲1或被選中,然後檢查ID爲'cna_number'的輸入是否爲空。如果是這樣,返回false。如果複選框被選中,它總是要求提交數據。我的問題是,它只是有時表明,當'cna_number'等所需的輸入字段爲空時,會出現錯誤。在第一次提交時,它總是會指出這些字段是必需的。但是,如果您再次提交表單,則不會指出這些字段是必需的,並且不會顯示錯誤消息 - 使用戶感到困惑。

我注意到複選框有一個隱藏的輸入。提交複選框並返回錯誤頁面時,隱藏輸入的值爲0,複選框的值爲1.您認爲這與問題有關嗎?

更新時間:

這裏是我認爲的代碼生成有關的表單字段:

echo $this->Form->inputs(array(
    'legend'=>'Certifications', 
    'rn_box'=>array(
     'type'=>'checkbox', 
     'label'=>'RN', 
     ), 
    'rn_number'=>array(
     'label'=>'RN Number:', 
     'value' => $results['Education']['rn_number'] 
     ), 
    'rn_exp_date' => array(
     'label' => 'Expiration Date:', 
     'dateFormat' => 'MDY', 
     'monthNames' => FALSE, 
     'minYear' => date('Y'), 
     'maxYear' => date('Y') + 20, 
     'empty' => TRUE, 
     'after' => '<span class="small">(MM/DD/YYYY)</span>', 
     'class' => 'input-mini', 
     'selected'=>strtotime($results['Education']['rn_exp_date']) 
     ), 
)); 

而控制器代碼:

public function pagethree() { 

     /** 
     ** If user has completed this form, 
     ** grab data for editing 
     **/ 
     $this->set('results', $this->Education->find('first', array( 
      'conditions' => array('Education.user_id' => $this->Auth->user('id')) 
     ))); 


     if ($this->request->is('post')){ 
      $this->request->data['User']['id'] = $this->Auth->user('id'); 

      /** 
      ** Find if there is any data 
      ** in this user in the Basics 
      ** table. 
      **/ 
      $existingRecordId = $this->Education->find('first', array( 
       'conditions' => array('Education.user_id' => $this->Auth->user('id')), 
       'fields' => array('Education.id') 
      )); 

      /** 
      ** If data exists, return row 
      ** id (PK). Set this value to 
      ** id key, so saveAll() updates 
      ** existing row. 
      **/ 

      if(sizeof($existingRecordId)>0) 
       $this->request->data['Education']['id'] = $existingRecordId['Education']['id']; 

      if ($this->User->saveAll($this->request->data)) { 
       $this->redirect(array('action'=>'pagefour')); 
      } else { 
       $this->Session->setFlash('Your data have not been saved'); 
      } 
     } 
    } 
+0

,你就必須按控制器代碼,併爲該視圖代碼。我們無法讀懂:) – mark

+0

k :)對不起。我用更多的代碼更新了這些問題。 –

回答

0

好,有你有它。使用valueselected從來都不是一個好主意。特別是如果你想在提交之後堅持表單並且無效。

您應該使用default或從控制器做到這一點: http://www.dereuromark.de/2010/06/23/working-with-forms/ 章「默認值」

+0

謝謝!那就是訣竅。我在控制器中的數據數組上運行了一個foreach循環,並將所有數據完美地配對。我假設會有與數據匹配的問題。再次感謝! –