We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Default paramater

Hi,

In regards to routing controllers with defined parameters, is there a way to default a parameter to something if it was empty?

Suppose you have the following:

 $id  = $this->dispatcher->getParam('id');
 $page = $this->dispatcher->getParam('page');

which would then produce the result:

site.com/id/page

Assume afterwards, you were to do the following:

site.com/id

would there be a way to default the second parameter to let's say 1 if it was not defined? such as doing something like:

 $page = $this->dispatcher->getParam('id');

if (!$page) {
return $this->response->redirect("idhere/1");
}

Any help would be appreciated. Thanks in advance.

Hi @Brian you have to define 2 routes like this

$router->add('/{idParam:[0-9]+}/{pageParam:[a-z0-9-]+}', ['controller' => 'index', 'action' => 'index'])->setName('idAndPage');
$router->add('/{idParam:[0-9]+}', ['controller' => 'index', 'action' => 'index'])->setName('onlyId');

Routing docs



3.7k

Hi @Brian you have to define 2 routes like this

$router->add('/{idParam:[0-9]+}/{pageParam:[a-z0-9-]+}', ['controller' => 'index', 'action' => 'index'])->setName('idAndPage');
$router->add('/{idParam:[0-9]+}', ['controller' => 'index', 'action' => 'index'])->setName('onlyId');

Routing docs

I get that, but my issue is that the page I am talking about is a news system which requires both the ID and the page number to be specified in order to properly load the controller. I would like to know if there is a way to detect you're missing the page paramater and being able to default it to page 1 for example.

sure the getParam() method has 3 parameters dispatcher docs

  1. name
  2. filter name (optional) filter docs
  3. default value (optional)
$page = $this->dispatcher->getParam('page', 'absint', false);

Good luck

edited Mar '18

Personally I don't use getParam(), opting for simple function parameters instead.

site.com/id/page will, by default, run the pageAction() method on the IdController class. So I'm assuming you've set up your routes to have that url point to a particular controller and action - let's say showAction()

You can absolutely do $page = $this->dispatcher->getParam('page', 'absint', false); as @emiliodeg suggested. Myself, I would just do this:


public function showAction($id=null,$page=1){
...
}