Getting View Object from within a Zend Controller plugin

Corey picture Corey · Feb 5, 2011 · Viewed 9.5k times · Source

In my controller, I have a postDispatch to consolidate my FlashMessenger messages:

public function postDispatch()
{       
    $messages = $this->_helper->getHelper ( 'FlashMessenger' )
        ->getMessages ();

    if ( $this->_helper->getHelper ( 'FlashMessenger' )
        ->hasCurrentMessages () )
    {
        $messages = array_merge ( $messages, $this->_helper->getHelper ( 'FlashMessenger' )
            ->getCurrentMessages () );
        $this->_helper->getHelper ( 'FlashMessenger' )
            ->clearCurrentMessages ();
    }

    $this->view->alert = $messages;
}

I want to make this into a Controller plugin.

UPDATE: I realized why I need this - I want to pass my flash messages in JSON when called by the JSON context. Unless the messages are added to the View object, I don't receive the messages.

I was able to get the messages into an array, but I don't know how to pass them to the view:

class Plugin_FlashMessenger extends Zend_Controller_Plugin_Abstract
{
    public function postDispatch($request)
    {
        $flashmessenger = Zend_Controller_Action_HelperBroker::getStaticHelper ( 'FlashMessenger' );

        $messages = $flashmessenger->getMessages ();
        if ( $flashmessenger->hasCurrentMessages () )
        {
            $messages = array_merge ( $messages, $flashmessenger->getCurrentMessages () );
            $flashmessenger->clearCurrentMessages ();
        }

        // THIS LINE IS WRONG. HOW DO I SEND $messages TO THE VIEW?
        $this->view->alert = $messages;
    }
}

Bonus question - is this the right way to accomplish this? Thanks!

Answer

Sonny picture Sonny · May 25, 2011

I found your post while searching for the same thing. Based on this thread, there are two simple ways to accomplish it.

One: If your view is initialized during bootstrap (resources.view[] = is in your application.ini), you can simply call this:

$view = Zend_Controller_Front::getInstance()
        ->getParam('bootstrap')
        ->getResource('view');

Two: If your view is not initialized during bootstrap:

$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
if (null === $viewRenderer->view) {
    $viewRenderer->initView();
}
$view = $viewRenderer->view;