如何在CakePHP表单验证失败时保存URL参数

问题描述:

我是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参数,还是有更好的方法来完成我完全缺少的操作?

任何意见将不胜感激。

的表单助手:: 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

您可以手动验证数据,然后使用您自己的重定向参数来保存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