Pragmatism in the real world

Access view variables in another view model

Unlike Zend Framework 1, the view layer in Zend Framework 2 separates the variables assigned to each view model. This means that when you are in the layout view script, you don’t automatically have access to variables that were assigned the the action’s view model and vice versa.

Accessing action variables in the layout

Consider this controller code:


class IndexController extends ActionController
{
public function indexAction()
{
return array('myvar' => 'test');
}
}

If you are in the layout.phtml, then to retrieve this value you do:

layout.phtml:

<?php
$children = $this->viewModel()->getCurrent()->getChildren();
$child = $children[0];
?>

<?php echo $this->escape($child->myvar);?>

If you really want to make sure you collect the correct child view model, then you could iterate over $children and look for the child that has the correct captureTo name set. For the action’s view model, this defaults to content:

layout.phtml:

<?php
$children = $this->viewModel()->getCurrent()->getChildren();
foreach($children as $child) {
if ($child->captureTo() == 'content') {
break;
}
}
?>

<?php echo $this->escape($child->myvar);?>

Accessing layout variables in the action view

If you have assigned a variable to the layout’s view model in, say, an event listener within Module.php:

Module.php:

public function onBootstrap($e)
{
$application = $e->getParam('application');
$viewModel = $application->getMvcEvent()->getViewModel();
$viewModel->some_config_var = '12345';
}

This is how you access some_config_var in the action view:

view/index/index.html:

<?php echo $this->escape($this->layout()->some_config_var); ?>

Another, more long winded way is to use the getRoot() method on the viewModel view helper:

view/index/index.html:

<?php
$layoutViewModel = $this->viewModel()->getRoot();
?>
<!-- Some HTML -->
<?php echo $this->escape($layoutViewModel->some_config_var); ?>

Setting configuration variables into the view

It therefore follows that if you need to set a variable that could be accessed from any view script, it’s easiest to set it into the layout’s view model and then access it via the layout() view script. This is handy for view layer config variables that you want to store in your config files, such as the Google search API key.

Application/config/module.config.php:

<?php
return array(
'layout' => array(
'google_search_api_key' => '1234567890',
),

Application/Module.php:

public function onBootstrap($e)
{
$application = $e->getParam('application');
$config = $e->getParam('config');

$viewModel = $application->getMvcEvent()->getViewModel();
$viewModel->config = $config->layout;
}

view/search/index.html:

<?php echo $this->layout()->config->google_search_api_key; ?>