How to redirect to home page from a subscriber file?

Hi

 

I am using the ProductEvents:: PRODUCT_LOADED_EVENT subscriber. I want to redirect to the home page in certain conditions. 

    public static function getSubscribedEvents(): array
    {
        return [
            ProductEvents::PRODUCT_LOADED_EVENT => ‘onProductLoaded’
        ];
    }

    public function onProductLoaded(EntityLoadedEvent $event)
    {

      
        //Some conditions
    if()
    {
        $pageVisible = false;
    }

        if(!$pageVisible)
        {

            // redirect to homepage
            return $this->redirectToRoute(‘frontend.home.page’);

        }

        return;
    }

How to redirect to the home page from a subscriber file?

If you want to redirect in Shopware way you have to use an event like “RequestEvent”.

    use Symfony\Component\HttpFoundation\RedirectResponse;
    use Symfony\Component\HttpKernel\Event\RequestEvent;
    use Symfony\Component\HttpKernel\KernelEvents;

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::REQUEST => 'onCmsPageLoaded'
        ];
    }


    public function onCmsPageLoaded(RequestEvent $event)
    {
        $request = $event->getRequest();

        $attributes = $request->attributes;

        $route = $attributes->get('_route');

        if($route == 'frontend.cms.page')
        {
	    $response = new RedirectResponse($this->router->generate('frontend.home.page'), 301);

	    $event->setResponse($response);

	    return;
        }
    }

 

Hi @abinjohnedamana,

how do you access event specific data in your case?

I need information about a logged in customer from the context but with the Kernel Request Event I don’t have access to the context anymore.

Vice versa I am not able to redirect if I use a non-kernel event

Hi @lucamario

You can try the following

KernelEvents::RESPONSE => 'onProductDetailPageLoaded',


public function onProductDetailPageLoaded(ResponseEvent $event): void
{
	if ($event->getResponse() instanceof StorefrontResponse) {
	    $this->checkCadcamOrScannerProduct($event);
	    return;
	}
}

public function checkCadcamOrScannerProduct($event)
{
	$route = $event->getRequest()->attributes->get('_route');


    /** @var StorefrontResponse */
    $response = $event->getResponse();

    /** @var SalesChannelContext */
    $salesChannelContext = $response->getContext();

    $customer = $salesChannelContext->getCustomer();

    if(!$customer)
    {
	 $response = new RedirectResponse($this->router->generate('frontend.home.page'), 301);

	    $event->setResponse($response);
    }

	return true;
}
2 Likes

Works perfect, thank you @abinjohnedamana !