0

I'm working on magento2.4 .Need to get the quantity of the product in product save after observer. while get qty it always returns null for newly created products.

Note:qty shows correctly for updating the product.

    <?php

namespace YOURNAMESPACE\YOURMODULENAME\Observer;

use Magento\Framework\Event\ObserverInterface;

class Productsaveafter implements ObserverInterface
{    
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $product = $observer->getEvent()->getProduct(); 
        $stockItem = $product->getExtensionAttributes()->getStockItem();
        $stockData = $stockItem->getQty();

    }   
}
2
  • can you post the code you have in th eobserver?
    – Marius
    Commented Mar 21, 2023 at 9:11
  • updated the code @Marius Commented Mar 21, 2023 at 11:36

1 Answer 1

0

Here is an example of how you can get the quantity of a newly created product in the catalog_product_save_after observer:

    use Magento\Framework\Event\Observer;
    use Magento\Framework\Event\ObserverInterface;
    use Magento\Catalog\Model\Product;

    class MyObserver implements ObserverInterface
    {
        protected $_stockRegistry;

        public function __construct(
            \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
        ) {
            $this->_stockRegistry = $stockRegistry;
        }

        public function execute(Observer $observer)
        {
            $product = $observer->getEvent()->getProduct();
            $productId = $product->getId();
            $stockItem = $this->_stockRegistry->getStockItem($productId);
            $qty = $stockItem->getQty();
            
            // Do something with the quantity information
        }
    }

In this example, we're using the StockRegistryInterface to get the stock information for the newly created product.

3
  • Not working..still qty is null for new products Commented Mar 21, 2023 at 11:37
  • ok wait let me update my code... could you please confirm a case like when you create a new product in Admin then right after that you want a qty of that product right ? Commented Mar 23, 2023 at 5:42
  • yes,want qty while creating new products in admin Commented Mar 23, 2023 at 10:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.