假设我在items
控制器中。
好的,假设我正在执行view
操作(url 类似于 /items/view/10012?date=2013-09-30
),其中列出了给定日期属于客户端的项目列表。
我想链接以添加新项目。我会像这样使用 htmlhelper: echo $this->Html('action'=>'add');
在我的add
操作中,我有一个表单,其中包含client_id
和item_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') );
}
为什么不使用正确的蛋糕网址参数?
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...
}
}