0

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.

  • You can look at https://stackoverflow.com/questions/16665010/access-controller-action-variables-to-zf2-layout – Alain Pomirol Oct 30 '19 at 08:03
  • 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. –  Oct 30 '19 at 22:53
  • 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. –  Oct 31 '19 at 11:48
  • 1
    You need to use a ViewHelper. Have a look at a [good book on getting started with ZF3](https://olegkrivtsov.github.io/using-zend-framework-3-book/html/en/Page_Appearance_and_Layout/Writing_Own_View_Helpers.html) – rkeet Nov 23 '19 at 08:30

2 Answers2

0

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

Angel Deykov
  • 1,199
  • 1
  • 9
  • 15
  • Does not work. The variables are only then accessible in the template but not the layout. I need to set the variable(s) in the controller and have access to to it in the layout, that is, the page / PHP script that contains the view / template. –  Oct 30 '19 at 22:59
0

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
Kembrick
  • 1
  • 3