How to disable layout and view renderer in ZF2?

26,787

Solution 1

Just use setTerminal(true) in your controller to disable layout.

This behaviour documented here: Zend View Quick Start :: Dealing With Layouts

Example:

<?php
namespace YourApp\Controller;

use Zend\View\Model\ViewModel;

class FooController extends AbstractActionController
{
    public function fooAction()
    {
    $viewModel = new ViewModel();
    $viewModel->setVariables(array('key' => 'value'))
              ->setTerminal(true);

    return $viewModel;
    }
}

If you want to send JSON response instead of rendering a .phtml file, try to use JsonRenderer:

Add this line to the top of the class:

use Zend\View\Model\JsonModel;

and here an action example which returns JSON:

public function jsonAction()
{
    $data = ['Foo' => 'Bar', 'Baz' => 'Test'];
    return new JsonModel($data);
}

EDIT:

Don't forget to add ViewJsonStrategy to your module.config.php file to allow controllers to return JSON. Thanks @Remi!

'view_manager' => [
    'strategies' => [
        'ViewJsonStrategy'
    ],
],

Solution 2

You can add this to the end of your action:

return $this->getResponse();

Solution 3

Slightly more info on the above answer... I use this often when outputting different types of files dynamically: json, xml, pdf, etc... This is the example of outputting an XML file.

// In the controller
$r = $this->getResponse();

$r->setContent(file_get_contents($filePath)); //

$r->getHeaders()->addHeaders(
    array('Content-Type'=>'application/xml; charset=utf-8'));

return $r;

The view is not rendered, and only the specified content and headers are sent.

Share:
26,787

Related videos on Youtube

Viszman
Author by

Viszman

hobby: programing in javascript and php

Updated on July 10, 2022

Comments

  • Viszman
    Viszman almost 2 years

    How can i disable layout and view renderer in Zend Framework 2.x? I read documentation and can't get any answers looking in google i found answer to Zend 1.x and it's

    $this->_helper->viewRenderer->setNoRender(true);
    $this->_helper->layout->disableLayout();
    

    But it's not working any more in Zend Framework 2.x. I need to disable both view renderer and layout for Ajax requests.

    Any help would be great.

  • Remi Thomas
    Remi Thomas over 10 years
    Don't forget to add this 'strategies' => array( 'ViewJsonStrategy', ), to you config.php from akrabat.com/zend-framework-2/…
  • babak faghihian
    babak faghihian about 9 years
    if we want to return viewModel with json encoding what should we do ?