0

I have this code to redirect to custom page from observer.
But I wonder how to redirect from observer, and with data transfer to the redirected page.

<?php

namespace Namespace\Module\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Response\RedirectInterface;

class MyObserver implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        // do something

        // redirect
        $this->redirectToMyCustomPage($observer);

        return $this;
    }

    public function redirectToMyCustomPage($observer) {
        // get error url
        $url = '/namespace/module/action';

        // setting an action flag to stop processing further hierarchy
        $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);

        /// redirecting to error page
        $observer->getControllerAction()->getResponse()->setRedirect($url);
        return $this;
    }
}

1 Answer 1

0

Ah found it.
We only need to transfer params through the url, like this:

<?php

namespace Namespace\Module\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Response\RedirectInterface;

class MyObserver implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        // do something

        // redirect
        $this->redirectToMyCustomPage($observer);

        return $this;
    }

    public function redirectToMyCustomPage($observer) {
        // get error url
        $url = '/namespace/module/action?myparams=abc';

        // setting an action flag to stop processing further hierarchy
        $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);

        /// redirecting to error page
        $observer->getControllerAction()->getResponse()->setRedirect($url);
        return $this;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.