Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a different view in controller action of ZF2

How to render a different view other than default in controller action. by default it try to find the same view as action in the view folder but I would like render different view available in views folder for controler action.

We can do this ZF1 like this $this->_helper->viewRenderer('foo');

Can Anyone know, how to achieve above in Zendframework 2?

We can disabled the view using

$response = $this->getResponse();
        $response->setStatusCode(200);
        $response->setContent("Hello World");
        return $response;

I don't know how to change/render a different view in zf2.

like image 296
Developer Avatar asked Aug 24 '12 11:08

Developer


2 Answers

can be done using

public function abcAction()
{
    $view = new ViewModel(array('variable'=>$value));
    $view->setTemplate('module/controler/action.phtml'); // path to phtml file under view folder
    return $view;
}

Thanks to akrabat for covering almost every scenario.

like image 187
Developer Avatar answered Oct 22 '22 10:10

Developer


My solution in Zend Framewor 2 is simple. For index action i prefer to call parrent::indexAction() constructor bcs we extend Zend\Mvc\Controller\AbstractActionController . Or just return array() in indexAction. ZF will atomaticly return index.pthml whitout definig what must be returned.

return new ViewManager() is the same return array()

<?php

 namespace Test\Controller;

 use Zend\Mvc\Controller\AbstractActionController,
     Zend\View\Model\ViewModel;

 // Or if u write Restful web service then use RestfulController
 // use Zend\Mvc\Controller\AbstractRestfulController

 class TestController extends AbstractActionController
 {
    /*
     * Index action
     *
     * @return main index.phtml
     */

     public function indexAction()
     {
          parent::indexAction();

          // or return new ViewModel();
          // or much simple return array();
     }

    /*
     * Add new comment
     *
     * @return addComment.phtml
     */

     public function addAction()
     {
         $view = new ViewManager();
         $view->setTemplate('test/test/addComment.phtml');  // module/Test/view/test/test/

      return $view;
     }

Dont forget to configure route and view_manager in module/config/module_config

  'view_manager' => array(
        'template_path_stack' => array(
            'Test' => __DIR__ . '/../view',
        ),
    ),
like image 2
Jony Avatar answered Oct 22 '22 08:10

Jony