0
votes

I'm using zend MVC 3.1.1 and trying to pass variables from the called controller action to the layout but having real difficulties finding a way to do so. I haven't found a solution online for this problem.

Here is my base controller 'render' method that gets called to create the view model.

    protected function render ( array $data = array () ) {
        $controller = '';
        $action = '';

        $controller = strtolower( preg_replace( "/^(.*)\\\/", "", $controller ) );

        $data[ 'controller' ] = $controller;
        $data[ 'action' ] = $action;

        $viewModel = new ViewModel( $data );

        $viewModel->setTemplate( $controller . "/{$action}.php" );

        return $viewModel;
    }

And here is a snipped of my layout.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title><!-- I WANT TO PUT VARIABLE HERE --></title>
    </head>
    <body>
            <?=$this->content?>
    </body>
</html>

How can I pass a variable from the controller 'render' action, or anywhere else in the execution, and have access to it in the same way I do to '$this->content'?

Thank you.

2
This does not work for me. I need to use the variable in the layout page, not the template / view and I need to pass it from the controller. This method allows me to access the variable in the view but not the layout that contains it.user1769908
Yes. I've tried that a number of times but the only variable that I have access to in the layout is $this->content. Doing a print_r even only shows $this->content as accessible variables.user1769908
You need to use a ViewHelper. Have a look at a good book on getting started with ZF3rkeet

2 Answers

0
votes

Try

....
$viewModel = new ViewModel();

$viewModel->setVariables(
   [
      'controller' => $controller,
      'action' => $action,
   ]
);

$viewModel->setTemplate( $controller . "/{$action}.php" );

return $viewModel;
...

You can find setVariables() method description inside vendor/zendframework/zend-view/src/Model/ViewModel.php

0
votes

In Zend 1.x you can set variable in controller like this

$this->view->layout()->isFlag = true;

and then catch it in layout

var_dump($this->layout()->isFlag);  // true