在创建插件时,如何在EventSubscriber中重定向?
我只是订阅了一个从PageLoadedEvent继承的特定事件。在我的方法中,我只想重定向到另一个页面。现在,我只能重定向,重写一个控制器,因为只有在控制器类中才有redirect -method。但我也只想重定向,在一个特定的事件被触发之后。
<?php declare(strict_types=1);
namespace My\Plugin\Storefront\Subscriber;
use Shopware\Storefront\Page\Account\Profile\AccountProfilePageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Psr\Container\ContainerInterface;
class Account implements EventSubscriberInterface {
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public static function getSubscribedEvents()
{
return [
AccountProfilePageLoadedEvent::class => 'onAccount'
];
}
public function onAccount(AccountProfilePageLoadedEvent $event) {
/**
* @var Symfony\Bundle\FrameworkBundle\Controller\RedirectController $redirectController
*/
$redirectController = $this->container->get('Symfony\Bundle\FrameworkBundle\Controller\RedirectController');
return $redirectController->redirectAction($event->getRequest(), "frontend.home.page");
}
}我找到了RedirectController,我可以通过services.xml注入到我的订阅者。结果返回一个RedirectResponse。但是返回该对象不会发生任何事情。它应该重定向到主页。
发布于 2019-10-01 22:25:42
如果您订阅了PageLoadedEvent,则当前无法执行此操作。我在我们的内部问题跟踪器https://issues.shopware.com/issues/NEXT-5107中为此创建了一个票据
你可以跟着那里的州走。
在此期间,您可以尝试订阅\Symfony\Component\HttpKernel\KernelEvents::RESPONSE并在此处执行重定向。
来自Schöppingen的最好的问候
迈克尔·特尔格曼
发布于 2021-10-01 07:33:42
有点晚了,但使用RedirectResponse是可能的:
\Symfony\Component\HttpFoundation\RedirectResponse示例:
//if you want to redirect to controller which does not acepts xmlhttp request, you can use 201 response code as second argument
$response = new RedirectResponse($path);
$response->send();您可以使用Shopware Router生成路径(您可以通过DI将其附加到您的订阅者):
\Shopware\Storefront\Framework\Routing\Router示例:
$path = $this->router->generate('frontend.checkout.cart.page');https://stackoverflow.com/questions/58124147
复制相似问题