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

MVC route with optional param problem with generating correct route

Hello,

I have a problem with defiing a route with optional frangment on it. I saw that there's a possibility to use /:params but I would prefer not to. I would rather want to use a route with only pagination param defined as an optional like:

/my-controller/my-action(/page/{page:[0-9]+})?

This sadly doesn't work as expected. It generates me withing a route while using Url helper question mart at the end:

/my-controller/my-action?

Is there a possibility to do it using standard router, cause this would allow me to define a controller action like

public function myAction($page = 1) {}

?

Best regards



98.9k

Just create the routes that way:

<?php

$router = new Phalcon\Mvc\Router(false);

$router->add("/:controller/:action[/]?([0-9]+)?", array(
    'controller' => 1,
    'action' => 2,
    'page' => 3
));

This will work for matching route, but will not generate it correctly. I'm getting at the end of address

my-route[/]??

Was searching for similar problem solving. Here my answer https://stackoverflow.com/a/18205750/501831

edited Oct '15

I had the same problem and that's how I solved it:

routes.php

<?php
$method  = strtolower($this->di->getRequest()->getMethod());

$router = new \Phalcon\Mvc\Router(false);
$router->setUriSource(\Phalcon\Mvc\Router::URI_SOURCE_SERVER_REQUEST_URI);
$router->removeExtraSlashes(true);

$group = new \Phalcon\Mvc\Router\Group([
    'namespace' => 'Acme\Controller\Customer',
]);

$group->setPrefix('/customer');

$group->addGet('/address', [
    'controller' => 'address',
    'action'     => $method,
]);

$group->addGet('/address/{id:[a-z0-9]*}', [
    'controller' => 'address',
    'action'     => $method,
])
    ->setName('customer/address');

$group->addPost('/address', [
    'controller' => 'address',
    'action'     => $method,
]);

Result:

$this->url->get(['for' => 'customer/address']);

genetates example.com/customer/address and

$this->url->get(['for' => 'customer/address', 'id' => '123']);

generates example.com/customer/address/123



8.0k

try this

$group->addGet('/address(/.*)*', [
    'controller' => 'address',
    'action'     => $method,
    'id' => 1
])