0

Here is the code, please review and advise.

Demo/Test/etc/frontend/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="layout_generate_blocks_before">
        <observer name="Demo_check_for_vision_user_session" instance="Demo\Test\Observer\CheckForTestUserSession" />
    </event>    
</config>

Demo/Test/Observer/CheckForTestUserSession.php

<?php

namespace Demo\Test\Observer;

use Psr\Log\LoggerInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Session\SessionManagerInterface;
use Magento\Framework\App\Request\Http;
use Magento\Framework\UrlInterface;
use Magento\Framework\App\ResponseFactory;
use Magento\Framework\App\Response\RedirectInterface;
/**
 * Class CheckForTestUserSession
 * @package Demo\Test\Observer
 */
class CheckForTestUserSession implements ObserverInterface
{
    /**
     * @var SessionManagerInterface
     */
    private $coreSession;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var Http
    */
    protected $request;

    /**
    * @var UrlInterface
    */
    protected $url;

    /**
    * @var ResponseFactory
    */
    protected $responseFactory;

    /**
    * @var RedirectInterface
    */
    protected $redirect;



    /**
     * constructor
     */
    public function __construct(
        LoggerInterface $logger,
        SessionManagerInterface $coreSession,
        Http $request,
        UrlInterface $url,
        ResponseFactory $responseFactory,
        RedirectInterface $redirect

    ) {
        $this->logger = $logger;
        $this->coreSession = $coreSession;
        $this->request = $request;
        $this->url=$url;
        $this->responseFactory = $responseFactory;
        $this->redirect = $redirect;

    }

    /**
     * Vision redirects a customer
     *
     * @param Observer $observer
     */
    public function execute(Observer $observer)
    {
        $action = $observer->getEvent()->getFullActionName();
        $SID= $this->request->getParam('SID');
        //$layout = $observer->getEvent()->getLayout();
        //$custId = $this->getRequest()->getParam('id');
        $writer = new \Zend\Log\Writer\Stream(BP.'/var/log/magento11.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        if($SID){       

        $controller = $observer->getControllerAction();
        $this->redirect->redirect($controller->getResponse(), 'checkout/cart');        
        }        
    }


}
3
  • Add this code in your execute and don't forget to return $this; in last. code : $url = $this->_urlInterface->getUrl('checkout/cart/index'); $observer->getControllerAction()->getResponse()->setRedirect($url); Nov 6, 2019 at 10:44
  • No luck @RohanHapani which is throwing Call to a member function getResponse() on null Nov 6, 2019 at 10:49
  • First, check that if condition execute or not. Put log in if condition. Nov 6, 2019 at 11:49

3 Answers 3

1

I am not sure why you are using "layout_generate_blocks_before" event to redirect to cart if current URL contains SID param. You can create a router file using following way.

etc/frontend/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\App\RouterList">
        <arguments>
            <argument name="routerList" xsi:type="array">
                <item name="redirect_if_sid" xsi:type="array">
                    <item name="class" xsi:type="string">Demo\Test\Controller\Router\RewriteSID</item>
                    <item name="disable" xsi:type="boolean">false</item>
                    <item name="sortOrder" xsi:type="string">20</item>
                </item>
            </argument>
        </arguments>
    </type>
</config>

Controller/Router/RewriteSID.php

<?php

namespace Demo\Test\Controller\Router;

class RewriteSID implements \Magento\Framework\App\RouterInterface
{
    protected $actionFactory;
    protected $_response;
    protected $storeManager;

    public function __construct(
        \Magento\Framework\App\ActionFactory $actionFactory,
        \Magento\Framework\App\ResponseInterface $response,
        \Magento\Store\Model\StoreManagerInterface $storeManager
    ) {
        $this->actionFactory = $actionFactory;
        $this->_response = $response;
        $this->storeManager = $storeManager;
    }

    public function match(\Magento\Framework\App\RequestInterface $request)
    {
        $identifier = $request->getOriginalPathInfo();

        $condition = new \Magento\Framework\DataObject(['identifier' => $identifier, 'continue' => true]);
        $identifier = $condition->getIdentifier();

        if ($condition->getRedirectUrl()) {
            $this->_response->setRedirect($condition->getRedirectUrl());
            $request->setDispatched(true);
            return $this->actionFactory->create('Magento\Framework\App\Action\Redirect');
        }

        if (!$condition->getContinue()) {
            return null;
        }

        if ($request->getParam('SID')) {
            $redirect_url = $this->storeManager->getStore()->getUrl('checkout/cart/index');
        }
        else
        {
            return null;
        }

        $this->_response->setRedirect($redirect_url);
        $request->setDispatched(true);
        return $this->actionFactory->create('Magento\Framework\App\Action\Redirect');
    }
}

This will redirect any url to shopping cart page if URL is somewhat as below.

http://yourdomain.com/anyurl/?SID=1

Try this and i guess it can perform the same result.

9
  • Thanks @Yashshah i will check and let you know Nov 6, 2019 at 13:07
  • I guess it worked for you. You can accept the answer if so. Also the previous one.
    – Yash Shah
    Nov 6, 2019 at 13:37
  • Hi @yash shah it seems cachable do you have any idea how to prevent. plz advise Dec 4, 2019 at 2:52
  • @NagarajuK, i think routing has nothing to do with caching. and you have a pretty staright condition to chec SID. So no cache should play a role. If you can elaborate the issue in detail, it would be great.
    – Yash Shah
    Dec 4, 2019 at 6:35
  • Sure I will explain you actually the first time when i use 127.0.0.1/magento2.3.1sampledata/?SID=value1 which is triggering 2nd time when I use 127.0.0.1/magento2.3.1sampledata/?SID=value2 on the same browser match method is not triggering even i tired with echo message and exit. Dec 4, 2019 at 7:33
0

You can change you Observer's code with below code

<?php

namespace Demo\Test\Observer;

use Psr\Log\LoggerInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Session\SessionManagerInterface;
use Magento\Framework\App\Request\Http;
use Magento\Framework\UrlInterface;
use Magento\Framework\App\ResponseFactory;
use Magento\Framework\App\Response\RedirectInterface;
/**
 * Class CheckForTestUserSession
 * @package Demo\Test\Observer
 */
class CheckForTestUserSession implements ObserverInterface
{
    /**
     * @var SessionManagerInterface
     */
    private $coreSession;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var Http
    */
    protected $request;

    /**
    * @var UrlInterface
    */
    protected $url;

    /**
    * @var ResponseFactory
    */
    protected $responseFactory;

    /**
    * @var RedirectInterface
    */
    protected $redirect;

    protected $_actionFlag;

    /**
     * constructor
     */
    public function __construct(
        LoggerInterface $logger,
        SessionManagerInterface $coreSession,
        Http $request,
        UrlInterface $url,
        ResponseFactory $responseFactory,
        RedirectInterface $redirect,
        \Magento\Framework\App\ActionFlag $actionFlag
    ) {
        $this->logger = $logger;
        $this->coreSession = $coreSession;
        $this->request = $request;
        $this->url=$url;
        $this->responseFactory = $responseFactory;
        $this->redirect = $redirect;
        $this->_actionFlag = $actionFlag;
    }

    /**
     * Vision redirects a customer
     *
     * @param Observer $observer
     */
    public function execute(Observer $observer)
    {
        $action = $observer->getEvent()->getFullActionName();
        $SID= $this->request->getParam('SID');
        //$layout = $observer->getEvent()->getLayout();
        //$custId = $this->getRequest()->getParam('id');
        $writer = new \Zend\Log\Writer\Stream(BP.'/var/log/magento11.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        if($SID){       

        $controller = $observer->getControllerAction();
        $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);
        $this->_redirect->redirect($controller->getResponse(), 'customer/account/create');
        }        
    }
}

I've added this line in your observer

$this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);

Hope this will help you!

5
  • 1
    Thanks @krishnan let me try and get back Nov 6, 2019 at 10:20
  • but i am getting Fatal error: Uncaught Error: Call to a member function getResponse() on null in Nov 6, 2019 at 10:24
  • Can you please check what you're getting here in this variable ? $controller = $observer->getControllerAction(); Nov 6, 2019 at 10:25
  • Not getting any value @krishan savaliya Nov 6, 2019 at 10:29
  • Can you please check your $observer's get_class_methods ? Nov 6, 2019 at 11:05
0
$redirectionUrl = $this->url->getUrl('checkout/cart');
$this->responseFactory->create()->setRedirect($redirectionUrl)->sendResponse();
3
  • @prince i have tried the above code but no luck Nov 6, 2019 at 10:31
  • try to keep only my code inside execute(Observer $observer) and remove everything else
    – PЯINCƎ
    Nov 6, 2019 at 10:35
  • No luck @prince Nov 6, 2019 at 10:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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