phpzend-frameworkzend-viewzend-framework3

ZF3: How to get view of an action from another action in the controller?


In my controller action, I want to grap a rendered full page of another action:

class MycontrollerController extends AbstractActionController
{
    public function firstactionAction()
    {
         $html = some_function_to_get_the_rendered_page_of_secondaction();
    }

    public function secondactionAction()
    {
         return new ViewModel();
    }
}

Solution

  • Be careful to use setTemplate()

    MycontrollerControllerFactory.php

    <?php
    
    namespace Application\Controller\Service;
    
    use Application\Controller\MycontrollerController;
    use Interop\Container\ContainerInterface;
    use Zend\ServiceManager\Factory\FactoryInterface;
    
    class MycontrollerControllerFactory implements FactoryInterface
    {
        public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
        {
            $controller = new MycontrollerController();
            $controller->setRenderer($container->get('Zend\View\Renderer\PhpRenderer'));
            return $controller;
        }
    }
    

    MycontrollerController.php

    <?php
    
    namespace Application\Controller;
    
    use Zend\Mvc\Controller\AbstractActionController;
    use Zend\View\Model\ViewModel;
    
    class MycontrollerController extends AbstractActionController
    {
        /**
         * @var \Zend\View\Renderer\PhpRenderer
         */
        protected $renderer;
    
        /**
         * @return \Zend\View\Renderer\PhpRenderer
         */
        public function getRenderer()
        {
            return $this->renderer;
        }
    
        /**
         * @param  \Zend\View\Renderer\PhpRenderer $renderer
         * @return self
         */
        public function setRenderer($renderer)
        {
            $this->renderer = $renderer;
            return $this;
        }
    
        public function firstAction()
        {
            if ($this->yourMethod()) {
                $secondView = $this->secondAction();
                $html = $this->getRenderer()->render($secondView);
            }
    
            $view = new ViewModel();
            $view->setTemplate('namespace/my-controller/first');
            return $view;
        }
    
        public function secondAction()
        {
            $view = new ViewModel();
            $view->setTemplate('namespace/my-controller/second');
            return $view;
        }
    }