1

I need to perform a operation when a product is deleted from admin. So I have created a observer using below code which is working fine.

Vendor/Module/etc/adminhtml/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="catalog_product_delete_after">
        <observer name="test_name" instance="Vendor\Module\Observer\ProductDeleteAfter" />
    </event>
</config>

Vendor\Module\Observer\ProductDeleteAfter.php

<?php

namespace Vendor\Module\Observer;

use Magento\Framework\Event\ObserverInterface;

class ProductDeleteAfter implements ObserverInterface
{    
   /**
     * @var ObjectManagerInterface
     */
    protected $_objectManager;

    /**
     * @param \Magento\Framework\ObjectManagerInterface $objectManager
     */
    public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectManager
    ) {
        $this->_objectManager = $objectManager;
    }

    /**
     * customer register event handler
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $_product = $observer->getProduct(); 
        $_sku=$_product->getSku();        
        die(var_dump($_sku));
    } 
}

Here I am getting only last selected product even though when I selected multiple products using checkbox. I want all the selected products Id or sku.

enter image description here

1 Answer 1

2

You need to update your observer function's code :

public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $_product = $observer->getEvent()->getProduct();
        $_sku = $_product->getSku();
        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/Rohan.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        $logger->info($_sku);
        return $this;
    }

Clean cache and check it.

6
  • thanks for you support but it's not working.. I'm getting the sale result.
    – Ramesh KR
    Jan 10, 2020 at 11:51
  • 1
    It's because, you stop execution using die. Jan 10, 2020 at 12:01
  • 1
    Check my updated answer and update your code. Check log file. You will get multiple skus. Jan 10, 2020 at 12:02
  • 1
    Happy to help !! Happy coding :) No, it's call on every product delete action. So, it will return one by one. Jan 10, 2020 at 12:07
  • 1
    Thanks I got what I need. You saved my day
    – Ramesh KR
    Jan 10, 2020 at 12:09

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.