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

And*_*ers 3 validation cakephp

我是cakephp的新手并试图用它编写一个简单的应用程序,但是我遇到了一些表单验证问题.

我有一个名为"Person"的模型,它有很多"PersonSkill"对象.要向一个人添加"PersonSkill",我已将其设置为调用这样的URL:

HTTP://本地主机/ MyApp的/ person_skills /添加/为person_id:3

我一直在通过person_id,因为我想显示我们为其添加技能的人的姓名.

我的问题是如果验证失败,则person_id参数不会持久保存到下一个请求,因此不会显示此人的姓名.

控制器上的add方法如下所示:

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());        
    }
}   
Run Code Online (Sandbox Code Playgroud)

在我的person_skill add.ctp中,我设置了一个隐藏字段,其中包含person_id,例如:

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

有没有办法在表单验证失败时持久化person_id url参数,或者是否有更好的方法来完成我完全缺失的?

任何建议将不胜感激.

nei*_*kes 6

FormHelper :: create()方法允许您在其创建的表单标记的action属性中配置URL.

您希望确保使用当前URL,以便发布到相同的URL,如果验证失败,则person_id命名参数仍然存在.

尝试这样的事情:

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

CakePHP应该将命名参数,即数组('person_id'=> 3)与当前控制器和操作合并,并返回与您相同的URL.

顺便说一下,如果$ this-> data不为空,你还想阅读人员详细信息并在视图中设置它们,所以我在控制器中丢失了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());        
}   
Run Code Online (Sandbox Code Playgroud)