abinjohnedamanaabinjohnedamana MemberComments: 36 Received thanks: 9 Member since: February 2019

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?

Answers

  • abinjohnedamanaabinjohnedamana MemberComments: 36 Received thanks: 9 Member since: February 2019

    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;
            }
        }

     

Sign In or Register to comment.