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

Int parameter on the indexAction

Hi,

I am trying to get a type int parameter to the function indexAction of my controller but it doesn't work.

When the user goes to the url "my-app/users", I want to display the list of users whereas when the user goes to the url "my-app/users/1", I want to display the details of the user having the identifier 1.

Here is the code of my function "indexAction":

public function indexAction(int $id = null)
{
    if(empty($id))
    {
        // Display the list of users
    }

    else
    {
        // Display the details of user
    }
}

So I added a var_dump($id) to te function indexAction and the value of $id remains NULL when I go to the url "my-app/users/1".

I must go to the url "my-app/users/1/1" if I want to define correctly the value of the parameter.

Is it normal?

How can I do it without a route?

Did you added anything to your routes or you are using default routes option?



4.3k

I think that I am using default routes option because I don't use the service "Phalcon\Mvc\Router".



4.3k

After all, I will use routes because it is the only solution that I know.

So, here are the modifications that I made on my project:

services.php

$di->set('router', function () {
  return include APP_DIR . '/config/routes.php';
});

routes.php

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

$router->add('/:controller/:int', array(
   'controller' => 1,
   'action' => 'index',
   'params' => 2
));

return $router;

It works perfectly, I will use that route into multiple controllers and that's why I used :controller in my file routes.php.