Raekye
Raekye

Reputation: 5131

How to pass data to layout in Zend 2?

I've looked around, and there are a few links about this in Zend 1 at best. The best solution I've found is

// controller:
return array('viewValue' => 'something');
// layout.phtml
$children = $this->viewModel()->getCurrent()->getChildren();
$viewValue = $children[0]->viewValue;

In the layout, but it seems a little kludgy. It's even stranger because when I do get_class_methods on the layout it doesn't show a viewModel() method. Basically, I've looked around the API (and source code) and haven't found much. Zend 1 also seems to have more access; some old solutions involved getting the view, and directly modifying it, but in Zend 2 we return a new array (or view model). Any tips?

As for why, I'm using a jQuery mobile layout. So the heading is separate from content, but the structure should be the same (should belong in the layout).

Upvotes: 1

Views: 877

Answers (2)

Jurian Sluiman
Jurian Sluiman

Reputation: 13558

The view models are hierarchically build. The top level view model is the "layout" and a child view model is injected after a controller is dispatched. This means you can build quite some tree of models for your application.

The top level view model (so the one representing the layout) is also located in the MvcEvent. That object is passed along in the application during bootstrap, but also linked to the controller when the controller is initialized.

The MvcEvent is accessible with $this->getEvent() in the controller, the view model by $event->getViewModel(). So to cut things short, just do this:

controller MyController
{
  public function myAction()
  {
    $this->getEvent()->getViewModel()->foo = 'bar';
  }
}

And in your layout.phtml:

<?php echo $this->foo; ?>

Upvotes: 4

Sam
Sam

Reputation: 16455

This pretty much is, how it is done. The new Zend\View-Components are pretty much all ViewModels nested into each other. Rob Allen has written a great article about it on how to work with variables throughout ViewModels.

Furthermore most often i think this approach isn't the best way. It'd be much better to have a ViewHelper or a Layout-Placeholder to do the job. Once again a great article has been written, this time by my dear Bakura, aka Michael Gallego.

Currently, either of those approaches would be your way to go.

Upvotes: 1

Related Questions