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

getParam() always returns null

I'm trying to get the project id from the url using the router. Let's say this is my URL: https://boardash.test/tasks/all/7 And I want to get the 7 in my controller.

I created a router using this:

$router->add('/tasks/:action/{project}', ['controller' => 'tasks', ':action' => 1]);

And try to access it using:

$this->dispatcher->getParam('project')

But when I var_dump() this, it returns null

What am I missing?

Where you try accessing it? In action? I'm not sure about this and this is my guess, but doesn't you need argument on method to have this in method body? Like:

public function allAction($project)
{

}
edited Jan '18

Yeah, that works indeed, but how can I use this in the controller initialize function? Isn't there something like a global parameter I can use?

public function initialize($project)
{
    $this->view->project = $project;
}

This does not work sadly

Where you try accessing it? In action? I'm not sure about this and this is my guess, but doesn't you need argument on method to have this in method body? Like:

public function allAction($project)
{

}

Oh then if you are talking about intialize method then yes, dispatcher on this point doesn't know yet about this parameter. It knows on stage when before action will be executed. Initialize method is fired only when controller is constructed and only once per request.

edited Jan '18

You could use the afterExecuteRoute event

// Controller context
public function afterExecuteRoute(Dispatcher $dispatcher)
{
    $project = $dispatcher->getParam('project');
}

https://docs.phalcon.io/bs/latest/dispatcher

Thanks, I'll try that out soon