0

When I am clicking on reorder from customer account I want to remove specific products from adding into my cart. For this I am using "controller_action_predispatch_sales_order_reorder" event which gets activated as soon as I click on reorder in my customer account.

Then I am getting my original order id and getting all the products related to it. Also, I have my array of disabled products as well. I have my cart also and from that I am checking whether product in the cart is in disabled list or not if yes, I have code to remove it but its not working as it is supposed to.

Am I using wrong event? if yes then which event should I go for? will "controller_action_postdispatch_sales_order_reorder" event work?

Here is my code

Event file:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<!--    Reorder from Admin side-->
<event name="sales_convert_order_to_quote">
    <observer name="admin_reorder" instance="VoltLighting\OrderInfo\Observer\AdminReorder"/>
</event>

<!--    Reorder from customer side-->
<event name="controller_action_predispatch_sales_order_reorder">
    <observer name="customer_reorder" instance="VoltLighting\OrderInfo\Observer\CustomerReorder"/>
</event>


<event name="checkout_onepage_controller_success_action">
    <observer name="customer_reorder_success" instance="VoltLighting\OrderInfo\Observer\CustomerReorderSuccess"/>
</event>
-->

Observer file:

<?php

namespace VoltLighting\OrderInfo\Observer;


use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Checkout\Model\Cart;
use Magento\Customer\Model\Session;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Api\OrderRepositoryInterface;

class CustomerReorder implements ObserverInterface
{
   protected $cart;
   protected $customerSession;
   protected $orderRepository;
   protected $productCollectionFactory;
   protected $disabledProducts = [];

public function __construct(Session $customerSession, OrderRepositoryInterface $orderRepository, Cart $cart, CollectionFactory $productCollectionFactory)
{
    $this->cart = $cart;
    $this->orderRepository = $orderRepository;
    $this->customerSession = $customerSession;
    $this->productCollectionFactory = $productCollectionFactory;
}
public function getDisabledProducts(): array
{
    $collection = $this->productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    $collection->addAttributeToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);
    foreach ($collection as $product) {
        $disabledSkus = $product->getSku();
        array_push($this->disabledProducts, $disabledSkus);
    }
    return $this->disabledProducts;
}

public function execute(Observer $observer)
{
    /*
     * get customer session and original order entity id
     */
    $order = $observer->getEvent();
    $entityId = $order->getRequest()->getParam('order_id');
    $customer = $this->customerSession;
    $parentOrderedSkus = [];
    /*
     * get order data based on order entity id
     */
    $orderData = $this->orderRepository->get($entityId);
    $allItems = $orderData->getAllItems();
    $incrementID = $orderData->getIncrementId();
    foreach ($allItems as $item) {
        $productSku = $item->getSku();
        array_push($parentOrderedSkus, $productSku);
    }
    /*
     * save it in session
     */
    $parentOrder = [$entityId, $incrementID, $parentOrderedSkus];
    $customer->setMyValue($parentOrder);

    $disabledSkus = [];
    $disabledSkus = $this->getDisabledProducts();
    array_push($disabledSkus, 'VDL-6009-4-BBZ');

    $cartQoute = $this->cart->getQuote();
    $cartitems = $cartQoute->getItemsCollection();

    foreach ($cartitems as $cartItem) {
        $productSku = $cartItem->getSku();
        if (in_array($productSku, $disabledSkus)) {
            /*$cartQoute->deleteItem($cartItem)->save();*/
            $itemID= $cartItem->getId();
            $this->cart->remove($itemID)->save();
        }
        /*$item->save();*/
    }
    $cartQoute->collectTotals();
}
}

This is the part where I am checking condition and if it exists I want to skip this product from adding it into my cart.

$cartQoute = $this->cart->getQuote();
    $cartitems = $cartQoute->getItemsCollection();

    foreach ($cartitems as $cartItem) {
        $productSku = $cartItem->getSku();
        if (in_array($productSku, $disabledSkus)) {
            /*$cartQoute->deleteItem($cartItem)->save();*/
            $itemID= $cartItem->getId();
            $this->cart->remove($itemID)->save();
        }
        /*$item->save();*/
    }
    $cartQoute->collectTotals();
}

I want this functionality only on Reorder

0

So I found the solution of my question and got it working. I am posting my code as an answer if anyone wants it.

What I was trying to do is remove all the disables products from my reorder and add rest of the products in the cart. Store desired information in Customer session and if our reorder contains disabled products the display a message in the cart checkout.

Here is my code if we are reordering from Customer account:

My events.xml file

app/code/VoltLighting/OrderInfo/etc/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">
<!--    Reorder from customer side-->
<event name="controller_action_postdispatch_sales_order_reorder">
    <observer name="customer_reorder" instance="VoltLighting\OrderInfo\Observer\CustomerReorder"/>
</event>
</config>

My observer.php file

app/code/VoltLighting/OrderInfo/Observer/CustomerReorder.php

<?php

namespace VoltLighting\OrderInfo\Observer;

use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Checkout\Model\Cart;
use Magento\Customer\Model\Session;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Message\ManagerInterface;
use Magento\Sales\Api\OrderRepositoryInterface;

class CustomerReorder implements ObserverInterface
{
   protected $cart;
   protected $customerSession;
   protected $orderRepository;
   protected $messageManager;
   protected $productCollectionFactory;
   protected $disabledProducts = [];

public function __construct(
    Session $customerSession,
    OrderRepositoryInterface $orderRepository,
    Cart $cart,
    CollectionFactory $productCollectionFactory,
    ManagerInterface $managerInterface
) {

    $this->cart = $cart;
    $this->messageManager = $managerInterface;
    $this->orderRepository = $orderRepository;
    $this->customerSession = $customerSession;
    $this->productCollectionFactory = $productCollectionFactory;
}

public function getDisabledProducts(): array
{
    $collection = $this->productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    $collection->addAttributeToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);
    foreach ($collection as $product) {
        $disabledSkus = $product->getSku();
        array_push($this->disabledProducts, $disabledSkus);
    }
    return $this->disabledProducts;
}

public function execute(Observer $observer)
{
    /*
     * get customer session and original order entity id
     */
    $order = $observer->getEvent();
    $customer = $this->customerSession;
    $entityId = $order->getRequest()->getParam('order_id');
    $parentOrderedSkus = [];
    /*
     * get order data based on order entity id
     */
    $orderData = $this->orderRepository->get($entityId);
    $incrementID = $orderData->getIncrementId();

    $disabledSkus = $this->getDisabledProducts();
    /*array_push($disabledSkus, 'VDL-6009-4-BBZ');*/

    $cartQoute = $this->cart->getQuote();
    $cartitems = $cartQoute->getAllItems();
    foreach ($cartitems as $cartItem) {
        $productSku = $cartItem->getSku();
        if (in_array($productSku, $disabledSkus)) {
            $cartQoute->deleteItem($cartItem)->save();
        } else {
            array_push($parentOrderedSkus, $productSku);
        }
    }
    /*
     * Save it in a  customer session
     * */
    $parentOrder = [$entityId, $incrementID, $parentOrderedSkus];
    $customer->setMyValue($parentOrder);

    /*
     * Save cart qoute with changes
     * */
    $cartQoute->setTriggerRecollect(1);
    $cartQoute->collectTotals()->save();

    if (count($parentOrderedSkus)  != count($cartitems)) {
        $this->messageManager->addError(__('Some of the products are discontinued.'));
    }

    return $this;
}
}

Here is my code if we are reordering from Admin account:

My events.xml file

app/code/VoltLighting/OrderInfo/etc/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">
 <!--    Reorder from Admin side-->
<event name="sales_convert_order_to_quote">
    <observer name="admin_reorder" instance="VoltLighting\OrderInfo\Observer\AdminReorder"/>
</event>
</config>

My observer.php file

app/code/VoltLighting/OrderInfo/Observer/AdminReorder.php

<?php

namespace VoltLighting\OrderInfo\Observer;

use Magento\Backend\Model\Auth\Session;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Message\ManagerInterface;

class AdminReorder implements ObserverInterface
{
   protected $backendAuthSession;
   protected $messageManager;
   protected $_productCollectionFactory;
   protected $disabledProducts = [];

public function __construct(Session $backendAuthSession, CollectionFactory $productCollectionFactory, ManagerInterface $managerInterface)
{
    $this->messageManager = $managerInterface;
    $this->backendAuthSession = $backendAuthSession;
    $this->_productCollectionFactory = $productCollectionFactory;
}

public function getDisabledProducts()
{
    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    $collection->addAttributeToFilter('status', Status::STATUS_DISABLED);
    foreach ($collection as $product) {
        $disabledSkus = $product->getSku();
        array_push($this->disabledProducts, $disabledSkus);
    }
    return $this->disabledProducts;
}

public function execute(Observer $observer)
{
    /*
     * find whether its a reorder or not
     */
    $order = $observer->getEvent()->getOrder();
    $entityId = $order->getEntityId();
    $incrementId = $order->getIncrementId();
    $parentOrderedSkus = [];

    /*
     * remove specific skus from qoute
     */
    $disabledSkus = $this->getDisabledProducts();
    /*array_push($disabledSkus, 'VDL-6009-4-BBZ');*/
    $quote = $observer->getEvent()->getQuote();
    $quoteItems = $quote->getAllItems();
    foreach ($quoteItems as $item) {
        $productSku = $item->getSku();
        if (in_array($productSku, $disabledSkus)) {
            $quote->deleteItem($item)->save();
            continue;
        } else {
            array_push($parentOrderedSkus, $productSku);
        }
    }
    $quote->collectTotals();

    /*
     * save entity id, increment id and its products skus in session
     */
    $parentOrder = [$entityId, $incrementId, $parentOrderedSkus];
    $adminUserName = $this->backendAuthSession;
    $adminUserName->setMyValue($parentOrder);

    if (count($parentOrderedSkus)  != count($quoteItems)) {
        $this->messageManager->addError(__('Some of the products are discontinued.'));
    }
}
}

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.