Chr Testo
Chr Testo

Reputation: 127

ZF2: add global variable to view

I'm trying to learn ZF2 and I need to find out about some basics. What I want to do is define certain variables that are available in all templates. I have an IndexController extendes BaseController and in BaseController I tried this:

public function onDispatch( \Zend\Mvc\MvcEvent $e ){
  $this->view->superImportantArray = array('data' => ...); 
}

Of course this is a ZF1 approach and doesn't work. So how do I do this? Would be thankful for any hint.

Upvotes: 0

Views: 487

Answers (1)

Tim Fountain
Tim Fountain

Reputation: 33148

Try and avoid using custom base controllers if you can. You can achieve this using the events system. Put use Zend\Mvc\MvcEvent; at the top of your Module.php, and then add:

public function onBootstrap(MvcEvent $e)
{
    $eventManager->attach(MvcEvent::EVENT_RENDER, function($e) {
        $layoutViewModel = $e->getViewModel();
        $childViewModels = $layoutViewModel->getChildren();
        if (count($childViewModels) == 0) {
            // probably an AJAX request
            return;
        }
        $viewModel = $childViewModels[0];

        $viewModel->superImportantArray = array('date' => ...);
    });
}

Upvotes: 1

Related Questions