My observer is not getting product information, this line is always printed
$this->logger->info(‘Product object is always null.’);
<?php
namespace CustomModuleObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkEventObserver;
use MagentoCatalogApiProductRepositoryInterface;
use PsrLogLoggerInterface;
class StockUpdate implements ObserverInterface
{
/**
* @var ProductRepositoryInterface
*/
protected $productRepository;
/**
* @var LoggerInterface
*/
protected $logger;
/**
* StockUpdate constructor.
* @param ProductRepositoryInterface $productRepository
* @param LoggerInterface $logger
*/
public function __construct(
ProductRepositoryInterface $productRepository,
LoggerInterface $logger
) {
$this->productRepository = $productRepository;
$this->logger = $logger;
}
public function execute(MagentoFrameworkEventObserver $observer)
{
$this->logger->info('Stock item saved.');
$product = $observer->getEvent()->getProduct();
// $event = $observer->getEvent();
$this->logger->info('Event Data: ' . json_encode($product->getData(), true));
$dataObject = $observer->getEvent()->getData('data_object');
$item = $observer->getEvent()->getData('item');
$name = $observer->getEvent()->getData('name');
$this->logger->info('Data Object: ' . json_encode($dataObject, true));
$this->logger->info('Item: ' . json_encode($item, true));
$this->logger->info('Name: ' . json_encode($name, true));
if ($product === null) {
$this->logger->info('Product object is always null.');
return;
}
And my events.xml file
<?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="cataloginventory_stock_item_save_after">
<observer name="custom_module_stock_update" instance="CustomModuleObserverStockUpdate" />
</event>
</config>
Snippet of output:
[2023-08-21T10:02:05.503413+00:00] report.INFO: Stock item saved. [] []
[2023-08-21T10:02:05.503751+00:00] report.INFO: Event Data: ["data_object","item","name"] [] []
[2023-08-21T10:02:05.503888+00:00] report.INFO: Data Object: {} [] []
[2023-08-21T10:02:05.504012+00:00] report.INFO: Item: {} [] []
[2023-08-21T10:02:05.504136+00:00] report.INFO: Name: "cataloginventory_stock_item_save_after" [] []