1

I am trying to override this controller \magento\module-sales\Controller\AbstractController\Reorder.php and would like to add an if statement to check if a product is still in stock or no.

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

namespace Magento\Sales\Controller\AbstractController;

use Magento\Framework\App\Action;
use Magento\Framework\Registry;
use Magento\Framework\App\Action\HttpPostActionInterface;

/**
 * Abstract class for controllers Reorder(Customer) and Reorder(Guest)
 *
 * @package Magento\Sales\Controller\AbstractController
 */
abstract class Reorder extends Action\Action implements HttpPostActionInterface
{
    /**
     * @var \Magento\Sales\Controller\AbstractController\OrderLoaderInterface
     */
    protected $orderLoader;

    /**
     * @var Registry
     */
    protected $_coreRegistry;

    /**
     * @param Action\Context $context
     * @param OrderLoaderInterface $orderLoader
     * @param Registry $registry
     */
    public function __construct(
        Action\Context $context,
        OrderLoaderInterface $orderLoader,
        Registry $registry
    ) {
        $this->orderLoader = $orderLoader;
        $this->_coreRegistry = $registry;
        parent::__construct($context);
    }

    /**
     * Action for reorder
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $result = $this->orderLoader->load($this->_request);
        if ($result instanceof \Magento\Framework\Controller\ResultInterface) {
            return $result;
        }
        $order = $this->_coreRegistry->registry('current_order');
        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();

        /* @var $cart \Magento\Checkout\Model\Cart */
        $cart = $this->_objectManager->get(\Magento\Checkout\Model\Cart::class);
        $items = $order->getItemsCollection();
        foreach ($items as $item) {
            try {
                $cart->addOrderItem($item);
            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                if ($this->_objectManager->get(\Magento\Checkout\Model\Session::class)->getUseNotice(true)) {
                    $this->messageManager->addNoticeMessage($e->getMessage());
                } else {
                    $this->messageManager->addErrorMessage($e->getMessage());
                }
                return $resultRedirect->setPath('*/*/history');
            } catch (\Exception $e) {
                $this->messageManager->addExceptionMessage(
                    $e,
                    __('We can\'t add this item to your shopping cart right now.')
                );
                return $resultRedirect->setPath('checkout/cart');
            }
        }

        $cart->save();
        return $resultRedirect->setPath('checkout/cart');
    }
}

this is the line that I want to add the if statement - basically inside the foreach item function.

foreach ($items as $item) {
            try {
                $cart->addOrderItem($item);
            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                if ($this->_objectManager->get(\Magento\Checkout\Model\Session::class)->getUseNotice(true)) {
                    $this->messageManager->addNoticeMessage($e->getMessage());
                } else {
                    $this->messageManager->addErrorMessage($e->getMessage());
                }
                return $resultRedirect->setPath('*/*/history');
            } catch (\Exception $e) {
                $this->messageManager->addExceptionMessage(
                    $e,
                    __('We can\'t add this item to your shopping cart right now.')
                );
                return $resultRedirect->setPath('checkout/cart');
            }
        }

What I did:

/**
     * @var \Magento\Sales\Controller\AbstractController\OrderLoaderInterface
     */
    protected $orderLoader;

    /**
     * @var Registry
     */
    protected $_coreRegistry;

    protected $_stockItemRepository;

    /**
     * @param Action\Context $context
     * @param OrderLoaderInterface $orderLoader
     * @param Registry $registry
     */
    public function __construct(
        Action\Context $context,
        OrderLoaderInterface $orderLoader,
        Registry $registry,
        \Magento\CatalogInventory\Model\Stock\StockItemRepository $stockItemRepository
    ) {
        $this->orderLoader = $orderLoader;
        $this->_coreRegistry = $registry;
        $this->_stockItemRepository = $stockItemRepository;
        parent::__construct($context);
    }

    /**
     * Action for reorder
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $result = $this->orderLoader->load($this->_request);
        if ($result instanceof \Magento\Framework\Controller\ResultInterface) {
            return $result;
        }
        $order = $this->_coreRegistry->registry('current_order');
        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();

        /* @var $cart \Magento\Checkout\Model\Cart */
        $cart = $this->_objectManager->get(\Magento\Checkout\Model\Cart::class);
        $items = $order->getItemsCollection();
        foreach ($items as $item) {
             $_productStock = $this->_stockItemRepository->get($item->getProductId());
             if($_productStock->getIsInStock()) {
            try {
                
                $cart->addOrderItem($item);
    
            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                if ($this->_objectManager->get(\Magento\Checkout\Model\Session::class)->getUseNotice(true)) {
                    $this->messageManager->addNoticeMessage($e->getMessage());
                } else {
                    $this->messageManager->addErrorMessage($e->getMessage());
                }
                return $resultRedirect->setPath('*/*/history');
            } catch (\Exception $e) {
                $this->messageManager->addExceptionMessage(
                    $e,
                    __('We can\'t add this item to your shopping cart right now.')
                );
                return $resultRedirect->setPath('checkout/cart');
            }
    }
        }

        $cart->save();
        return $resultRedirect->setPath('checkout/cart');
    }

I got this error Type Error occurred when creating object: Magento\Sales\Controller\Order\Reorder\Interceptor I think it's because of \Magento\CatalogInventory\Model\Stock\StockItemRepository $stockItemRepository contruct

This is a controller for reorder - It keeps on giving me an error, I'm wondering if my code looks correct or no? is there a better a way to do this?

7
  • It is not a good way to solve this problem Did you run command "php bin/magento setup:di:compile" so that dependency injection knows about it? Sep 22 '20 at 22:31
  • I'm still so new to Magento, what would be a better way to solve this? Sep 22 '20 at 22:33
  • a better approach would be listening to event "adminhtml_customer_orders_add_action_renderer" magentoextensions.org/documentation/… Sep 22 '20 at 22:33
  • Could you please explain a bit more about this? I'm still a bit confused. Thank you. Sep 22 '20 at 22:36
  • And why is that the better approach? Sep 22 '20 at 23:00
3

To check product quantity / stock on .phtml

app/code/Vendor/Module/view/frontend/templates/product/view/checkstock.phtml

<?php    
$_product = $block->getProduct();
    $productQty = $_product->getExtensionAttributes()->getStockItem()->getQty();

    if ($productQty > 0) {
        echo "IN Stock";
        //logic code for instock
    } else {
        echo "Out of Stock";
        //    out of stock logic here
    }
?>

you can add this checkstock.phtml file on the product page

app/code/Vendor/Module/view/frontend/layout/catalog_product_view.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="product.info.main">
            <block class="Magento\Catalog\Block\Product\View"
             after="product.info.price" as="checkstock" 
             template="Vendor_Module::product/view/checkstock.phtml"/>
        </referenceContainer>
    </body>
</page>
1
  • How can I use this in the controller? Sorry, I am still so new to Magento. Sep 23 '20 at 14:28
-1

You can check using this also

    /**
     * @var \Magento\Sales\Controller\AbstractController\OrderLoaderInterface
     */
    protected $orderLoader;

    /**
     * @var Registry
     */
    protected $_coreRegistry;

    protected $product;

    /**
     * @param Action\Context $context
     * @param OrderLoaderInterface $orderLoader
     * @param Registry $registry
     */
    public function __construct(
        Action\Context $context,
        OrderLoaderInterface $orderLoader,
        Registry $registry,
         \Magento\Catalog\Model\ProductFactory $product
    ) {
        $this->orderLoader = $orderLoader;
        $this->_coreRegistry = $registry;
        $this->product = $product;
        parent::__construct($context, $orderLoader, $registry);
    }

    /**
     * Action for reorder
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $result = $this->orderLoader->load($this->_request);
        if ($result instanceof \Magento\Framework\Controller\ResultInterface) {
            return $result;
        }
        $order = $this->_coreRegistry->registry('current_order');
        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();

        /* @var $cart \Magento\Checkout\Model\Cart */
        $cart = $this->_objectManager->get(\Magento\Checkout\Model\Cart::class);
        $items = $order->getItemsCollection();
        foreach ($items as $item) {
            $product_data = $this->product->create()->load($item->getProductId());
            if ($product_data->isAvailable()) {
                try {
                    $cart->addOrderItem($item);
                } catch (\Magento\Framework\Exception\LocalizedException $e) {
                    if ($this->_objectManager->get(\Magento\Checkout\Model\Session::class)->getUseNotice(true)) {
                        $this->messageManager->addNoticeMessage($e->getMessage());
                    } else {
                        $this->messageManager->addErrorMessage($e->getMessage());
                    }
                    return $resultRedirect->setPath('*/*/history');
                } catch (\Exception $e) {
                    $this->messageManager->addExceptionMessage(
                        $e,
                        __('We can\'t add this item to your shopping cart right now.')
                    );
                    return $resultRedirect->setPath('checkout/cart');
                }
            }
        }
        
        $cart->save();
        return $resultRedirect->setPath('checkout/cart');
    }
3
  • you can check this into this path vendor\magento\module-catalog\view\frontend\templates\product\list.phtml here you see how magento check In stock and Out of stock.
    – Msquare
    Sep 23 '20 at 5:21
  • how to override abstract class controller? Sep 23 '20 at 14:33
  • and it doesn't work when I ran php bin/magento setup:di:compile, gives me this error Errors during compilation: Magento\Sales\Controller\Guest\Reorder Missed required argument product in parent::__construct call. File: /vagrant/www/vendor/magento/module-sales/Controller/Guest/Reorder.php Sep 23 '20 at 21:20

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.