【问题标题】:CakePHP prepopulate form with data from a linkCakePHP 使用来自链接的数据预填充表单
【发布时间】:2013-10-22 10:29:17
【问题描述】:

假设我在我的 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') );
}

【问题讨论】:

  • 你在正确的轨道上。但是您应该在此处发布相关的控制器代码。你很可能有某种错误。

标签: php forms cakephp post get


【解决方案1】:

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

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

这将为您提供更好的 URL,例如:

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...

    }

}

【讨论】:

  • 完美。我知道应该有办法。这是正确的做法。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-11
  • 2012-05-10
  • 1970-01-01
  • 2015-02-09
  • 1970-01-01
相关资源
最近更新 更多