Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing multiple, single or none parameters through URL cakePHP

so I have the following controller function for adding events:

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

What I need to do in some cases is to pass only the id and service_id or project_id and to skip the year, month and day. I have tried to pass parameters as empty strings or nulls as following, but none of it seemed to work.

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

Any help is much appreciated.

like image 570
Domas Avatar asked May 05 '14 09:05

Domas


2 Answers

The easiest solution would probably to use query parameters. (I tend to not use named parameters anymore as CakePHP will drop them soon or later)

View:

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

Controller:

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

}

This way it would be easy to have only some of the parameters.

like image 74
nIcO Avatar answered Sep 27 '22 22:09

nIcO


Instead of passing them as /var/var/var, just use URL variables:

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

Then access them:

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

Feel free to check if they're set or not empty first...etc, but - seems to fit a lot better for what you're going for.

like image 41
Dave Avatar answered Sep 27 '22 22:09

Dave