2010-03-17 127 views
3

我是cakephp的新手,並試圖用它編寫一個簡單的應用程序,但是我遇到了一些表單驗證問題。如何在CakePHP表單驗證失敗時保存URL參數

我有一個名爲「Person」的模型,它有許多「PersonSkill」對象。要添加「PersonSkill」一個人,我已經將它設置成這樣調用一個網址:

http://localhost/myapp/person_skills/add/person_id:3

我一直在通過爲person_id,因爲我要顯示我們是人的名字添加技能。

我的問題是,如果驗證失敗,person_id參數沒有持久化到下一個請求,所以不會顯示該人員的姓名。

控制器上的添加方法如下:

function add() {   
    if (!empty($this->data)) {   
     if ($this->PersonSkill->save($this->data)) { 
      $this->Session->setFlash('Your person has been saved.'); 
      $this->redirect(array('action' => 'view', 'id' => $this->PersonSkill->id)); 
     }  
    } else { 
     $this->Person->id = $this->params['named']['person_id']; 
     $this->set('person', $this->Person->read());   
    } 
} 

在我person_skill add.ctp我設置的隱藏字段,其保持爲person_id,如:

echo $form->input('person_id', array('type'=>'hidden','value'=>$person['Person']['id'])); 

是否有辦法在表單驗證失敗時堅持person_id url參數,還是有更好的方法來完成我完全缺少的操作?

任何意見將不勝感激。

回答

6

的表單助手:: create()方法允許你配置URL在它創建的形式標記的action屬性。

您想要確保使用當前URL,以便發佈到相同的URL,並且如果驗證失敗,那麼person_id命名參數仍然存在。

嘗試是這樣的:

echo $form->create('PersonSkill', array('url' => $this->params['named'])); 

CakePHP的應該合併命名的參數,可以即陣列(「PERSON_ID」 => 3)當前控制器和動作,並返回相同的URL,你都在。

順便說一句,你還需要閱讀的人的詳細信息,並設置他們在視圖中可用,如果$這個 - >數據是不是空的,所以我會失去else語句控制器,只是有:

function add() {   
    if (!empty($this->data)) {   
     if ($this->PersonSkill->save($this->data)) { 
      $this->Session->setFlash('Your person has been saved.'); 
      $this->redirect(array(
       'action' => 'view', 
       'id' => $this->PersonSkill->id 
      )); 
     }  
    } 
    $this->Person->id = $this->params['named']['person_id']; 
    $this->set('person', $this->Person->read());   
} 
+0

謝謝 - 這正是我所需要的! – 2010-03-18 09:33:53

+0

即使整潔,如果它們已經存在,它也不會重複參數。優秀的解決方 – Cruachan 2011-08-30 20:25:46

0

您可以手動驗證數據,然後使用您自己的重定向參數來保存URL參數。例如,

if(!empty($this->data)) { 
if($this->PersonSkill->validates()) { 
    if($this->PersonSkill->save($this->data) { 
    ... 
    } 
    else { // invalid data 
    $this->redirect(array('action' => 'view', 'id' => $this->PersonSkills->id)); 
    } 
} 
} 

從上控制器驗證手動在http://book.cakephp.org/view/410/Validating-Data-from-the-Controller