0

Doing url redirects is an easy thing rewriting a controller class, as $this->resultRedirectFactory is accessible as it is one of default injected objects

But, can we use this in plugins? I've been trying different ways, with no success

For instance... let's say I want to write plugin for \Magento\Multishipping\Controller\Checkout\Addresses controller execute() method, ignoring all logic & just redirecting to checkout/cart

Can someone provide how we could do this in a plugin with the 3 possible approaches (before, around & after)? Full code of the plugin class would be great, as my main problem is I haven't understand yet about how plugin parameters work

UPDATE

Not 100% sure, but I believe I tried same code as kirby solution yesterday, but using before plugin and saw constructor errors in frontend...

2

The plugin type depends on what you need. I guess, "after" and "around" could work for you.

The manual about plugins is here: http://devdocs.magento.com/guides/v2.2/extension-dev-guide/plugins.html

I suppose, you may declare a redirect factory and use it.

Let's say you will have static redirection. Your code could look like this:

namespace My\Module\Controller\Some;

use Magento\Framework\App\Action\Context;
use \Magento\Multishipping\Controller\Checkout\Addresses as AddressesAction;

class AddressesActionPlugin
{
    /**
     * @var \Magento\Framework\Controller\Result\RedirectFactory
     */
    protected $resultRedirectFactory;

    /**
     * @param Context $context
     */
    public function __construct(
        Context $context
    ) {
        $this->resultRedirectFactory = $context->getResultRedirectFactory();
    }

    /**
     * Plugin method
     */
    public function aroundExecute(AddressesAction $subject, callable $proceed)
    {
        // here, maybe do some logic with $subject - action-controller instance

        return $this->resultRedirectFactory->create()
            ->setPath(
                'some/where/else',
                [
                    'my-param' => 123,
                ]
            );
    }
}

Please note, I haven't tested this code. Feel free to change it if there are some mistakes.

  • I will try this & give you feedback – Raul Sanchez Mar 1 '18 at 8:49
  • It is working ;) – Raul Sanchez Mar 1 '18 at 9:00
  • Cool! I was glad to help! ;) – Kirby Mar 1 '18 at 16:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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