首页 > 解决方案 > 使用插件 Magento 2 更改控制器重定向 url

问题描述

我已经从控制器重定向,我想更改插件内的重定向 url。

这就是它目前的样子。

控制器:

        ...
        $this->messageManager->addSuccessMessage(__('Invitation to corporate account accepted.'));
        $this->corporateManagement->setCorporateSessionVars($customer->getId());

        return $this->_redirect($this->_url->getUrl('corporate/users'));

我想将该重定向更改为重定向到另一个 url(必须带有插件)。这就是我试图通过插件和插件工作来实现这一点的方式 $result 已更改,但用户仍被重定向到控制器内的 url,而不是来自插件的 URL。

插入:

    public function afterExecute(\Iways\Corporate\Controller\Invitation\Accept $subject, $result)
    {
        $corporateBranding = $this->corporateBrandingManagement->getCorporateBranding();

        if ($corporateBranding && $corporateBranding->getStoreGroupId()) {
            $storeGroup = $this->storeManager->getGroup($corporateBranding->getStoreGroupId());
            $store = $this->storeManager->getStore($storeGroup->getDefaultStoreId());
            $redirectUrl = $store->getBaseUrl().'corporate/users';
            $result = $this->redirect->getRedirect($redirectUrl);
        }

        return $result;
    }

重要提示:所有属性和方法都正常工作,$result 填充了另一个重定向并返回 $result,但用户被重定向到控制器的 url,而不是插件的 URL。

标签: magentomagento2magento-2.3

解决方案


在这种情况下,您可以尝试around改用after. 在周围并且不返回 $proceed() 只是返回您在插件中使用的值。

我没有对此进行测试,但我相信它应该可以工作。

    public function aroundExecute(\Iways\Corporate\Controller\Invitation\Accept $subject, $proceed)
    {
        $proceed();
        $corporateBranding = $this->corporateBrandingManagement->getCorporateBranding();

        if ($corporateBranding && $corporateBranding->getStoreGroupId()) {
            $storeGroup = $this->storeManager->getGroup($corporateBranding->getStoreGroupId());
            $store = $this->storeManager->getStore($storeGroup->getDefaultStoreId());
            $redirectUrl = $store->getBaseUrl().'corporate/users';
            $result = $this->redirect->getRedirect($redirectUrl);
        }

        return $result;
    }


推荐阅读