0

I override the controller Product/view.php

<?php
/**
 *
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Magenticians\AddModule\Controller\Rewrite\Product;

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

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

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

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


    protected $_categoryFactory;
    protected $_productFactory;

    Protected $customerSession;


    /**
     * 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,
        \Magento\Customer\Model\Session $customerSession,
        PageFactory $resultPageFactory,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Catalog\Model\ResourceModel\CategoryFactory $categoryFactory
    )
    {
        $this->viewHelper = $viewHelper;
        $this->resultForwardFactory = $resultForwardFactory;
        $this->resultPageFactory = $resultPageFactory;

        $this->_categoryFactory = $categoryFactory;
        $this->_productFactory = $productFactory;
        $this->customerSession = $customerSession;

        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->_request->getParam('___from_store')
                    && $this->_request->isPost()
                    && $this->_request->getParam(self::PARAM_NAME_URL_ENCODED)) {

                    $product = $this->_initProduct();
                    $cats = $product->getCategoryIds(); // All Categories of $product you will get in array format eg. array(catid 1, catid 2, catid 3


                    if (!$product) {
                        return $this->noProductRedirect();
                    }else if ($product && (!($this->customerSession->isLoggedin())) && ($cats == 8)) {
                        die ("ggggggggggggggggg44444444444");


                        $this->customerSession->setAfterAuthUrl($this->_url->getCurrentUrl());
                        $this->customerSession->authenticate();
                        die ("ggggggggggggggggg");

                    }


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



    }


}

Below the di.xml file code.

<?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\Category\View" type="Magenticians\AddModule\Controller\Rewrite\Category\View" />
    <preference for="Magento\Catalog\Controller\Product\View" type="Magenticians\AddModule\Controller\Rewrite\Product\View" />
</config>

But even when i try with var_dump there is no result can any one tell me the error in my code.

1
  • have you tried after di compile and cache flush your code perfect.
    – kunj
    Aug 30 '18 at 11:36
0

Just check one by one what values you are getting in these 3 values.

$this->_request->getParam('___from_store')

  $this->_request->isPost()

  $this->_request->getParam(self::PARAM_NAME_URL_ENCODED)

only these conditions are not satisfying that's why below code is running every time in you controller.

// 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;
        }
2
  • i want that not loged in customer to detailed product that exists in category number (id) 8 will be redirected to login page Aug 30 '18 at 12:50
  • can you please explain to me the functionnality of this if if (!$this->_request->getParam('___from_store') && $this->_request->isPost() && $this->_request->getParam(self::PARAM_NAME_URL_ENCODED)) Aug 30 '18 at 12:51
0

Create a module and add the below code to your 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\Catalog\Controller\Product\View">
        <plugin name="vendor_module_product_controller_view" type="Vendor\Module\Plugin\Catalog\Controller\Product\View" sortOrder="1"/>
    </type>
</config>

Create Plugin file like below under:

app/code/Vendor/Module/Plugin/Catalog/Controller/Product/View.php

and add the below content to the file:

<?php
namespace Vendor\Module\Plugin\Catalog\Controller\Product;

use Magento\Framework\App\Action\Context;

class View
{
    protected $customerSession;
    protected $urlInterface;

    public function __construct(
        Context $context,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Framework\UrlInterface $urlInterface
    ) {
        $this->customerSession = $customerSession;
        $this->urlInterface = $urlInterface;
    }

    public function aroundExecute(
        \Magento\Catalog\Controller\Product\View $subject,
        \Closure $proceed
    )
    {
        if(!$this->customerSession->isLoggedin())
        {
            $this->customerSession->setAfterAuthUrl($this->urlInterface->getCurrentUrl());
            $this->customerSession->authenticate();
        }
        return $proceed();
    }
}

Run set upgrade, di compile and other required commands and test.

2
  • it is my first time with plugin and other question i want that not loged in customer for my specific category ca't access to detailes page i see here in your code that you just tested on loged in customer, thanks again to your replay Aug 30 '18 at 12:31
  • What do you exactly want? Above code redirects the guest customer to login when accessing any product details page. Aug 30 '18 at 13:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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