sudhir
sudhir

Reputation: 41

Redirection from ZEND framework 2 Controller's Constructor

I want to check for user id in the constructor of my ZF2 Controller and if it is not defined then want to redirect to any external URL or to other controller I have tried:

$this->redirect()->toRoute("campaign");

and

$this->redirect()->toUrl("http://example.com");

Both approaches give me the same error message:

Url plugin requires that controller event compose a router; none found

Upvotes: 4

Views: 1820

Answers (1)

Arslaan Ejaz
Arslaan Ejaz

Reputation: 1001

Service Locator is not present in the Controller's constructor, but you can override onDispatch method inherited from AbstractActionController. Use it like this:

public function onDispatch(\Zend\Mvc\MvcEvent $e)
    {
        $session = new \Zend\Session\Container('base');
            if(!$session->offsetExists('id'))
            $this->redirect()->toRoute("campaign"); and $this->redirect()->toUrl("http://example.com")

        return parent::onDispatch($e);
    }

Upvotes: 8

Related Questions