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

How to get current router name?

Hi,

I'm trying to get the current router name in my view I defined before like this:

    $router->add(
         '/session/start', array(
               'module' => 'frontend',
              'namespace' => 'Frontend\Controllers',
              'controller' => 'session',
              'action' => 'start'
        )
    )->setName('session-start');

So, I need "session-start" when I am at "/session/start". I found this but it doesn't work:

    \Phalcon\DI::getDefault()->get('router')->getMatchedRoute()->getName();


85.5k

this works for me ( i use \Phalcon\Mvc\Router\Group tho dont know if it mastters ).

just out of curiosity, why cant you start it in the begging of the sessionAction() in Frontend\Controllers\sessionController.php ? and more important why dont you start it in index.php ? :D



14.4k
edited Jul '16

@Izo can you tell me exactly what you do? I will explain it afterwards :) "session-start" was just an example.



85.5k
edited Jul '16

in this file : Frontend\Controllers\sessionController.php you have function sessionAction, in its first line why dont you put session_start() there

or you dont wanna do that .. :D



85.5k

ok, where do you dump this \Phalcon\DI::getDefault()->get('router')->getMatchedRoute()->getName() ?



14.4k

I need it inside a javascript value. To be specific inside a partial view.



85.5k

hmm it should be working. this is working for me

$this->add('/:controller/:action/:params', [
                'controller' => 1,
                'action' => 2,
                'params' => 3
            ])
            ->setName('home-action');
    }

if you try it on top of your main view file, because it makes sence there to be matched route in order this to show you something, perhaps you dont have a matched route ?



11.6k

hi,

in your controller action


        $currentController = $this->dispatcher->getControllerName();
        $currentAction = $this->dispatcher->getActionName();
        $this->view->ctrl = $currentController;
        //or json rep.

then assign values to view and in your html file (if it's at page load), or do your json rep.

    <script>
     var controller = '{{ ctrl }}';  //volt syntax
     ...
     </script>