Search code examples
phpzend-framework2widgetviewhelper

ZF2 widgets/views in layout


I am working on a website where I need a "widget" like view in my layout of Zend Framework 2. the widget should show the operational status of the server (this is done).

(Correct me if this is bad MVC style) I have build a controller with the

function viewStatusAction(){ 
   ... 
   return $viewModel(array($vars))
}

then i want to use a viewHelper to get the status of the action. This is where I'm stuck. I know how to create the viewHelper, but not where to start to get the returned view from the controller action. So how do i do this?


Solution

  • Here is what i did. This should also be the right way to do it

    in module.php

    public function getViewHelperConfig()
    {
        return array(
            'factories' => array(
                'statusWidget' => function ($sm) {
                    -- some service handling --
                    $statusWidget = new statusWidget($service);
                    return $statusWidget;
                }
            )
        );
    }
    

    then i created a viewHelper in operationalStatus\View\Helper

    <?php
    namespace operationalStatus\View\Helper;
    
    use Zend\View\Helper\AbstractHelper;
    
    class statusWidget extends AbstractHelper
    {
    
        public function __construct($service){
            $this->service = $service
        }
    
        public function __invoke()
        {
            -- collect data from the service --
    
            return $this->getView()->render('operational-status/widget/status', array('operation' => $status));
        }
    
    }