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

Get data sent to view before render

Hi, I have a problem.

I need to catch data/vars that will be sent to view from controller. For example: controller do something, but before render view I need to decide what to do, to render as usual or to use this data in other way. Is it possible? I'm tried to attach listeners to view and dispatch events, but probably I can't find where can I get required data.

Thanks in advance.



98.9k

Use getParamsToView():

foreach ($this->view->getParamsToView() as $key => $value) {
    echo $key;
}

Thanks for the reply, but this only works for setVars (as expected).

class SessionController extends ControllerBase
{
    public function indexAction()
    {
        $this->view->setVar("test_key", 'test_value');

        if (!$this->request->isPost()) {
            Tag::setDefault('email', '[email protected]');
            Tag::setDefault('password', 'phalcon');
        }
    }
}

I would like to catch email and password. My injection to dispatcher in main (bootstrap) file:

    $di->set('view', function() use ($config, $di) {

        $eventsManager = $di->getShared('eventsManager');

        $eventsManager->attach('view:beforeRender', function($event, $view) {
            var_dump($view->getParamsToView()); // 'test_value' here OK
        });

        $view = new \Phalcon\Mvc\View();

        $view->setViewsDir(__DIR__ . $config->application->viewsDir);

        $view->registerEngines(array(
            ".volt" => 'volt'
        ));

        $view->setEventsManager($eventsManager);

        return $view;
    });

There are no method in static Tag class such as getParams or something. I'm tried to find it in DI tag service too.