CakePHP使用链接中的数据预填充表单

时间:2013-10-22 10:29:17

标签: php forms cakephp post get

假设我在我的items控制器中。

好的说我在我的view行动(网址类似于/items/view/10012?date=2013-09-30),其中列出了在给定日期属于客户的项目列表。

我想链接添加新项目。我会像这样使用htmlhelper: echo $this->Html('action'=>'add');

在我的add操作中,我的表单中包含client_iditem_date等字段。

当我在view行动中时,我知道这些值,因为我正在查看特定日期的特定客户的项目。我想将这些变量传递给我的add操作,以便在表单上预填充这些字段。

如果我在link'?' => array('client_id'=>$client_id))中添加查询字符串,则会中断添加操作,因为如果请求不是POST,则会发出错误。如果我使用form->postLink我会收到另一个错误,因为添加操作的POST数据只能用于添加记录,而不是传递数据以预填表单。

我基本上想让view页面上的链接将这两个变量传递给控制器​​中的add操作,这样我就可以定义一些变量来预填表单。有没有办法做到这一点?

这是我的add控制器代码。它的内容可能与我上面的问题略有不同,因为我试图稍微简化一下这个问题,但这个概念仍然适用。

public function add(){
    if ($this->request->is('post')) {
        $this->Holding->create();
        if ($this->Holding->save($this->request->data)) {
            $this->Session->setFlash(__('Holding has been saved.'), 'default', array('class' => 'alert alert-success'));
            return $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Unable to add your holding.'), 'default', array('class' => 'alert alert-danger'));
    }
    $this->set('accounts', $this->Holding->Account->find('list'));
        $sedol_list = $this->Holding->Sedol->find('all', array(
            'fields' => array(
                'id', 'sedol_description'
                ),
            'recursive' => 0,
            'order'  => 'description'
            )
        );
        $this->set('sedols', Hash::combine($sedol_list, '{n}.Sedol.id', '{n}.Sedol.sedol_description') );
}

1 个答案:

答案 0 :(得分:4)

为什么不使用正确的Cake URL参数?

echo $this->Html->link('Add Item', array(
    'action' => 'add',
    $client_id,
    $item_date
));

这会为您提供更好的网址,例如:

http://www.example.com/items/add/10012/2013-09-30

然后在您的控制器中,修改函数以接收这些参数:

public function add($client_id, $item_date) {

    // Prefill the form on this page by manually setting the values
    // in the request data array. This is what Cake uses to populate
    // the form inputs on your page.
    if (empty($this->request->data)) {

        $this->request->data['Item']['client_id'] = $client_id;
        $this->request->data['Item']['item_date'] = $item_date;

    } else {

        // In here process the form data normally from when the
        // user has submitted it themselves...

    }

}
相关问题