1

hi all, i want to override Magento\Catalog\Controller\Product\View.php file i tried to override but it's not loading the product page.

<?php
/**
 *
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Catalog\Controller\Product;

use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
use Magento\Framework\App\Action\HttpGetActionInterface as HttpGetActionInterface;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Catalog\Controller\Product as ProductAction;

/**
 * View a product on storefront. Needs to be accessible by POST because of the store switching.
 */
class View extends ProductAction implements HttpGetActionInterface, HttpPostActionInterface
{
    /**
     * @var \Magento\Catalog\Helper\Product\View
     */
    protected $viewHelper;

    /**
     * @var \Magento\Framework\Controller\Result\ForwardFactory
     */
    protected $resultForwardFactory;

    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * Constructor
     *
     * @param Context $context
     * @param \Magento\Catalog\Helper\Product\View $viewHelper
     * @param \Magento\Framework\Controller\Result\ForwardFactory $resultForwardFactory
     * @param PageFactory $resultPageFactory
     */
    public function __construct(
        Context $context,
        \Magento\Catalog\Helper\Product\View $viewHelper,
        \Magento\Framework\Controller\Result\ForwardFactory $resultForwardFactory,
        PageFactory $resultPageFactory
    ) {
        $this->viewHelper = $viewHelper;
        $this->resultForwardFactory = $resultForwardFactory;
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    /**
     * Redirect if product failed to load
     *
     * @return \Magento\Framework\Controller\Result\Redirect|\Magento\Framework\Controller\Result\Forward
     */
    protected function noProductRedirect()
    {
        $store = $this->getRequest()->getQuery('store');
        if (isset($store) && !$this->getResponse()->isRedirect()) {
            $resultRedirect = $this->resultRedirectFactory->create();
            return $resultRedirect->setPath('');
        } elseif (!$this->getResponse()->isRedirect()) {
            $resultForward = $this->resultForwardFactory->create();
            $resultForward->forward('noroute');
            return $resultForward;
        }
    }

    /**
     * Product view action
     *
     * @return \Magento\Framework\Controller\Result\Forward|\Magento\Framework\Controller\Result\Redirect
     */
    public function execute()
    {
        // Get initial data from request
        $categoryId = (int) $this->getRequest()->getParam('category', false);
        $productId = (int) $this->getRequest()->getParam('id');
        $specifyOptions = $this->getRequest()->getParam('options');

        if ($this->getRequest()->isPost() && $this->getRequest()->getParam(self::PARAM_NAME_URL_ENCODED)) {
            $product = $this->_initProduct();

            if (!$product) {
                return $this->noProductRedirect();
            }

            if ($specifyOptions) {
                $notice = $product->getTypeInstance()->getSpecifyOptionMessage();
                $this->messageManager->addNoticeMessage($notice);
            }

            if ($this->getRequest()->isAjax()) {
                $this->getResponse()->representJson(
                    $this->_objectManager->get(\Magento\Framework\Json\Helper\Data::class)->jsonEncode([
                        'backUrl' => $this->_redirect->getRedirectUrl()
                    ])
                );
                return;
            }
            $resultRedirect = $this->resultRedirectFactory->create();
            $resultRedirect->setRefererOrBaseUrl();
            return $resultRedirect;
        }

        // Prepare helper and params
        $params = new \Magento\Framework\DataObject();
        $params->setCategoryId($categoryId);
        $params->setSpecifyOptions($specifyOptions);

        // Render page
        try {
            $page = $this->resultPageFactory->create();
            $this->viewHelper->prepareAndRender($page, $productId, $this, $params);
            return $page;
        } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
            return $this->noProductRedirect();
        } catch (\Exception $e) {
            $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
            $resultForward = $this->resultForwardFactory->create();
            $resultForward->forward('noroute');
            return $resultForward;
        }
    }
}

Please check Code

Vendor\Module\Controller\Product\View.php

<?php

namespace Vendor\Module\Controller\Product;

use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
use Magento\Framework\App\Action\HttpGetActionInterface as HttpGetActionInterface;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Catalog\Controller\Product as ProductAction;


class View extends Magento\Catalog\Controller\Product\View
{
    /**
     * @var \Magento\Catalog\Helper\Product\View
     */
    protected $viewHelper;

    /**
     * @var \Magento\Framework\Controller\Result\ForwardFactory
     */
    protected $resultForwardFactory;

    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * Constructor
     *
     * @param Context $context
     * @param \Magento\Catalog\Helper\Product\View $viewHelper
     * @param \Magento\Framework\Controller\Result\ForwardFactory $resultForwardFactory
     * @param PageFactory $resultPageFactory
     */
    public function __construct(
        Context $context,
        \Magento\Catalog\Helper\Product\View $viewHelper,
        \Magento\Framework\Controller\Result\ForwardFactory $resultForwardFactory,
        PageFactory $resultPageFactory
    ) {
        $this->viewHelper = $viewHelper;
        $this->resultForwardFactory = $resultForwardFactory;
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    /**
     * Product view action
     *
     * @return \Magento\Framework\Controller\Result\Forward|\Magento\Framework\Controller\Result\Redirect
     */
    public function execute()
    {
        echo "Product view New action";exit;
        // Get initial data from request
        //$customCode = (int) $this->getRequest()->getParam('Code');


    }
}

etc/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">
   <preference for="Magento\Catalog\Controller\Product\View" 
            type="Vendor\Module\Controller\Product\View" />
</config>

If you have any idea please guide me thanks in Advance.

6
  • Whay you have try to overide this? And which issue you are facing there? Jun 21, 2019 at 14:23
  • @DhirenVasoya i want to hit the product url directly and need to be redirect to our custom controller Jun 21, 2019 at 14:27
  • Do you try anything? share that code and issue which you are facing into that one. Jun 21, 2019 at 14:28
  • @DhirenVasoya please check my updated question. Jun 21, 2019 at 14:34
  • 1
    @HiteshBalpande take a look at here - magento.stackexchange.com/questions/159565/… Jun 21, 2019 at 14:35

1 Answer 1

0

i have recently override this controller

etc/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">
    <preference for="Magento\Catalog\Controller\Product\View" type="Vendor\Module\Controller\Rewrite\Product\View" />
</config>

controller file

Vendor\Module\Controller\Rewrite\Product\View.php

<?php

    namespace Vendor\Module\Controller\Rewrite\Product;
    use Magento\Framework\App\Action\Context;
    use Magento\Framework\View\Result\PageFactory;
    class View extends \Magento\Catalog\Controller\Product\View
    {
        /**
         * @return \Magento\Framework\Controller\Result\Redirect|\Magento\Framework\View\Result\Page
         */

        Protected $customerSession;

        public function __construct(
            Context $context,
            \Magento\Catalog\Helper\Product\View $viewHelper,
            \Magento\Framework\Controller\Result\ForwardFactory $resultForwardFactory,
            \Magento\Customer\Model\Session $customerSession,
            PageFactory $resultPageFactory
        ) {
            $this->viewHelper = $viewHelper;
            $this->resultForwardFactory = $resultForwardFactory;
            $this->resultPageFactory = $resultPageFactory;
            $this->customerSession=$customerSession;
            parent::__construct($context, $viewHelper, $resultForwardFactory,$resultPageFactory);
        }

        protected function noProductRedirect()
        {
            $store = $this->getRequest()->getQuery('store');
            if (isset($store) && !$this->getResponse()->isRedirect()) {
                $resultRedirect = $this->resultRedirectFactory->create();
                return $resultRedirect->setPath('');
            } elseif (!$this->getResponse()->isRedirect()) {
                $resultForward = $this->resultForwardFactory->create();
                $resultForward->forward('noroute');
                return $resultForward;
            }
        }

        public function execute()
        {
    // Do your stuff here
            try{
                    // Get initial data from request
                    $categoryId = (int) $this->getRequest()->getParam('category', false);
                    $productId = (int) $this->getRequest()->getParam('id');
                    $specifyOptions = $this->getRequest()->getParam('options');

                    if ($this->getRequest()->isPost() && $this->getRequest()->getParam(self::PARAM_NAME_URL_ENCODED)) {
                        $product = $this->_initProduct();
                        if (!$product) {
                            return $this->noProductRedirect();
                        }
                        if ($specifyOptions) {
                            $notice = $product->getTypeInstance()->getSpecifyOptionMessage();
                            $this->messageManager->addNotice($notice);
                        }
                        if ($this->getRequest()->isAjax()) {
                            $this->getResponse()->representJson(
                                $this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode([
                                    'backUrl' => $this->_redirect->getRedirectUrl()
                                ])
                            );
                            return;
                        }
                        $resultRedirect = $this->resultRedirectFactory->create();
                        $resultRedirect->setRefererOrBaseUrl();
                        return $resultRedirect;
                    }

                    // Prepare helper and params
                    $params = new \Magento\Framework\DataObject();
                    $params->setCategoryId($categoryId);
                    $params->setSpecifyOptions($specifyOptions);

                    // Render page
                    try {
                        $page = $this->resultPageFactory->create();
                        $this->viewHelper->prepareAndRender($page, $productId, $this, $params);
                        return $page;
                    } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
                        return $this->noProductRedirect();
                    } catch (\Exception $e) {
                        $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
                        $resultForward = $this->resultForwardFactory->create();
                        $resultForward->forward('noroute');
                        return $resultForward;
                    }

            }catch(Exception $e){

            }
            return parent::execute();
        }
    }

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.