通过URL cakePHP传递多个,单个或无参数

时间:2014-05-05 09:53:25

标签: cakephp cakephp-2.0

所以我有以下控制器功能来添加事件:

public function add($id = null, $year = null, $month = null, $day = null, $service_id = null, $project_id = null){
...
}

在某些情况下我需要做的是只传递id和service_id或project_id并跳过年,月和日。我试图将参数作为空字符串或空值传递如下,但它们似乎都不起作用。

echo $this->Html->link('Add event', array(
    'controller' => 'events',
    'action' => 'add',
25, null, null, null, 3, 54
))

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:12)

最简单的解决方案可能是使用查询参数。 (我倾向于不再使用命名参数,因为CakePHP将很快或稍后删除它们)

查看:

echo $this->Html->link(__('add event'), array('controller' => 'events', 'action' => 'add', '?' => array('id' => 123, 'service_id' => 345, ...)));

控制器:

public function add(){
    $id         = isset($this->request->query['id'])         ? $this->request->query['id']         : null;
    $year       = isset($this->request->query['year'])       ? $this->request->query['year']       : null;
    $service_id = isset($this->request->query['service_id']) ? $this->request->query['service_id'] : null;
    ...

}

通过这种方式,只有一些参数很容易。

答案 1 :(得分:1)

不要将它们作为/var/var/var传递,而只使用网址变量:

www.whatever.com?id=123&month=4

然后访问它们:

$id = $this->request->query['id'];
$month= $this->request->query['month'];
... etc

随意检查他们是否先设置或不先清空......等等,但是 - 似乎更符合你的目标。