View helpers and variables not available in layout

I got a really strange problem while implementing a menu with Zend_Navigation. I added this piece of code in the Bootstrap.php:

    protected function _initNavigation()
    {
        $this->bootstrap('layout');
        $layout = $this->getResource('layout');
        $view = $layout->getView();
        $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/navigation.ini');
 
        $navigation = new Zend_Navigation($config);
        $view->navigation($navigation);
    }

This is fine for creating a menu or breadcrumbs, but there is one big problem: after this code is in use, all custom variables and the View Helper Include path are not available any more in the layout phtml file.

For example “echo $this->name” just echoes null. Or the custom view helper “$this->myHelper()” cannot be found because the View Helper include path only contains the path to Zend View Helpers.

And writing the same code in the phtml file of a simple action does work!

So what is the relation between the code above and the problems mentioned?

It all starts at the first line of the function “_initNavigation()”: there is a bootstrap function for the layout. Unfortunately it is necessary to add another line to not have the problems above. It is needed to also bootstrap the view! So the code becomes:

    protected function _initNavigation()
    {
        $this->bootstrap('layout');
        $this->bootstrap('view');
        $layout = $this->getResource('layout');
        $view = $layout->getView();
        $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/navigation.ini');
 
        $navigation = new Zend_Navigation($config);
        $view->navigation($navigation);
    }

Now the layout AND the view are bootstrapped, and the custom view helpers and variables can again be used in the layout phtml file.

I found this interesting issue in the ZF Jira: ZF-9537. It has already been reported, but it is not an issue (see status). So this is supposed to be normal behaviour? Does anyone has a good explanation for this?

2 thoughts on “View helpers and variables not available in layout”

  1. Have a look at Zend_Application_Resource_Navigation.
    _initXXX methods are executed before any application.ini-defined resources. If the order of resource-execution is important and you already use resources through application.ini, using application.ini to define the resource, lets you put it after the initialization of View and Layout.

    One downturn: the out-of-the box use of the Navigation resource requires you to define the whole navigation in application.ini. If that is not what you want, you can extend the class and create your Application_Resource_Navigation in a few lines of code which uses something like a “configPath” application.ini-setting to read the separate navigation.ini so you do not have to change your structure.

Comments are closed.