Question

Hi i have a zf2 application. In my module i attach a listener to the MvcEvent::EVENT_DISPATCH event. In this listener i check if the user is authenticated etc. If the user is authenticated i change the layout.

Now if i call $viewModel->setTerminal(true) in my action no content is shown, just the layout but i need it the other way around.

https://stackoverflow.com/a/21441607/1594076 This answer somewhat explains what wrong i think but it's not real clear to me. Also the solution provided is not working in my situation as i would have to add the 2 methods to all my controllers.

Anybody that has a solution?

Thanks

Was it helpful?

Solution

In your layout listener you'll need to apply some conditional logic to determine if the view model your controller returned is terminal before setting a layout.

This can be done by getting the result from the MvcEvent in your listener and checking it's a ViewModel instance that doesn't terminate()

public function yourLayoutListenerCallback(MvcEvent $e)
{
    // get the dispatched result from the event 
    $result = $e->getResult();
    // check it's a view model that doesn't terminate 
    if (!$result instanceof \Zend\View\Model\ViewModel || $result->terminate()) {
        // do nothing
        return;
    }
    // your existing layout logic ....
}

Note: you'll need to make sure your layout listener has a low enough priority (>= -10 seems to be enough) such that your controller action has actually returned the view model before testing the condition.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top