2012-06-01 66 views
0

在我的控制器中,我添加了($ id = null)函數。如果iput添加/ 43它的作品。但是,如果任何驗證失敗它不加/ 43重新加載。 (在顯示錯誤信息之後)。 怎麼辦..版本1.3 控制器:添加函數時出錯

function add($id = null) {  
if (!empty($this->data)) {  
       $this->ConsultingDet->create(); 
     if ($this->ConsultingDet->save($this->data)) { 
      $this->Session->setFlash('The consulting det has been saved', true); 
      $this->redirect(array('controller' => 'patients', 'action' => 'home')); 
     } else { 
      $this->Session->setFlash('The consulting det could not be saved. Please,  try again.', true); 
     } 
    } 
    if (is_null($id)) { 
     $this->set('id', 0); 
    } 

}
add.ctp:

<div class="consultingDets form"> 
<?php echo $this->Form->create('ConsultingDet');?> 
<fieldset> 
    <div class="sub1"> 
     <?php 

     echo $this->Form->input('patient_id', array('type' => 'hidden', 'value' => $patient['Patient']['id'])); 
     if ($id>0)  //This (id) brings out error on redirection 
      echo $this->Form->input('id',array('type' => 'hidden', 'value' => $id)); 
      echo $this->Form->input('temperature'); 
     ?>    
    </div>   
</fieldset> 
<?php echo $this->Form->end(__('Submit', true)); ?>  

+0

因爲你會渲染視圖添加?如果驗證是錯誤的,您可以重定向到引用者。 – Bob

+0

也許是因爲你沒有設置id(順便說一句,它非常罕見,試圖添加一個沒有被驗證過的對象) – Yises

回答

0

你可以試試這個:

function add($id = null) {  
    if (!empty($this->data)) {  
       $this->ConsultingDet->create(); 
     if ($this->ConsultingDet->save($this->data)) { 
      $this->Session->setFlash('The consulting det has been saved', true); 
      $this->redirect(array('controller' => 'patients', 'action' => 'home')); 
     } else { 
      $this->Session->setFlash('The consulting det could not be saved. Please, try again.', true); 
      //redirect to referrer page 
      $this->redirect($this->referer());   
     } 
    } 
    if (is_null($id)) { 
     $this->set('id', 0); 
    } 
+0

在這種情況下,FLash消息即將到來,但驗證消息沒有出現。 – alexkd

+0

對不起,重定向不是要走的路。 :) – Bob

1
<?php echo $this->Form->create(null, array('url' => 
      array('controller' => 'consultingdets', 'action' => 'add', $id))); ?> 
//<form action="consultingdets/add/43" 

基本上通過id你需要作爲參數的形式。通過這種方式,當您提交併驗證失敗時,Cake重定向到正確的URL(即使用您需要的id作爲參數)

您的控制器名稱可能有所不同。

+0

仍然錯誤即將到來。表單行爲=「consultingdets/add/43」表單在查看源頁面時(在使用您的答案之前)已經顯示。 – alexkd

+0

如果($ id> 0){} -in add.ctp-在這裏顯示'undefined variable' – alexkd

+0

@alexkd這將解決您的問題,重定向時會出現什麼問題(驗證失敗後)。 – Bob