Leo Galleguillos
Leo Galleguillos

Reputation: 2730

zend framework 3 - how to disable layout for entire controller

In Zend Framework 3, is it possible to disable the layout for an entire controller, preferably in the __construct() or onDispatch() methods?

I know that I can disable the layout for specific actions, for example:

public function indexAction()
{
    $view = new \Zend\View\Model\ViewModel();
    $view->setTerminal(true);
    return $view;
}

However, I would like to disable the layout for all actions in the controller without having to copy and paste the above code in every action.

Upvotes: 1

Views: 289

Answers (1)

Alain Pomirol
Alain Pomirol

Reputation: 828

In your Module class :

public function onBootstrap(MvcEvent $e)
{
    $sharedEvents = $e->getApplication()
        ->getEventManager()
        ->getSharedManager();
    $sharedEvents->attach(__NAMESPACE__, 'dispatch',
        function ($e) {
            if ($e->getRouteMatch()->getParam('controller') == '[your controller name in lowercase]') {
                $result = $e->getResult();
                if ($result instanceof \Zend\View\Model\ViewModel) {
                    $result->setTerminal(true);
                } else {
                    throw new \Exception(
                      __METHOD__ . ' expected \Zend\View\Model\ViewModel');
                }
            }
        });
}

Upvotes: 2

Related Questions