I searched for the same and got some answer about it, but did not help.
Those way I tried are as follows:
1)
in onBootstrap($e) function:
$e->getViewModel()->setVariable('test_variable', 'Hello World!');
//or
$e->getViewModel()->test_variable = 'Hello World!';
2) I created a function in Module.php
function boforeDispatch(MvcEvent $event) {
$event->getViewModel()->setVariable('test_variable', 'Hello World!');
//or
$event->getViewModel()->test_variable = 'Hello World!';
}
and called this function inside the onBootstrap($e) function
$application = $e->getApplication();
$eventManager = $application->getEventManager();
$eventManager->attach(MvcEvent::EVENT_DISPATCH, array($this, 'boforeDispatch'), 100);
when I tried in view
echo $test_variable;
it gives undefined variable test_variable in ...
error all the times.
Any idea?
Try using render event (MvcEvent::EVENT_RENDER
) instead:
public function onBootstrap($event){
$application = $event->getApplication();
$eventManager = $application->getEventManager();
$events->attach(MvcEvent::EVENT_RENDER, array($this, 'addVariablesToViewModel'), 100);
}
public function addVariablesToViewModel($event)
{
$viewModel = $this->getEvent()->getViewModel();
$viewModel->setVariables(array(
'key' => 'value',
));
}
Your view model is probably not yet available on (pre) dispatch