1

I want to delete the Disable product completely, through Observer! Programatically Like if we have a Disable Product, We have to delete it.

Product is disabled an event is triggered and remove that product from customers cart

0
1

Create a Test Module, in which create these files

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="customer_login">
        <observer name="custom_customer_log_login" instance="Example\New\Observer\UpdateCartAfterCustomerLoginAtObserver"/>
    </event>
</config>

observer/UpdateCartAfterCustomerLoginAtObserver.php

<?php

namespace Example\Test\Observer;

use \Magento\Framework\Message\ManagerInterface ;

class UpdateCartAfterCustomerLoginAtObserver implements \Magento\Framework\Event\ObserverInterface{


    /**
     * @var \Magento\Checkout\Model\Cart
     */
    protected $_customerCartSession;

    /**
     * @var \Magento\Catalog\Model\ProductRepository
     */
    protected $_productRepository;

    /**
     * @var \Magento\Checkout\Model\Session
     */
    protected $_checkoutSession;

    /**
     * @var \Magento\Catalog\Model\Product
     */
    protected $_productModel;

    /**
     * @param \Magento\Checkout\Model\Cart $cart
     * @param \Magento\Checkout\Model\Session $checkoutSession
     * @param \Magento\Catalog\Model\Product $productModel
     */
    public function __construct
    (
        \Magento\Checkout\Model\Cart $cart,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Catalog\Model\Product $productModel
    ){
        $this->_customerCartSession = $cart;
        $this->_checkoutSession = $checkoutSession;
        $this->_productModel = $productModel;
    }


    public function execute(\Magento\Framework\Event\Observer $observer){

        $customer = $observer->getEvent()->getCustomer();
        $cartItems = $this->_checkoutSession->getQuote()->getAllItems();

        foreach ($cartItems as $item) {
            $product = $this->_productModel->load($item->getProductId());
            if(!$product->getStatus())
                $this->_customerCartSession->removeItem($item->getItemId())->save();
        }

        return true;

    }

}

This is work for me:)

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.