1

I’m using the observer event called checkout_cart_product_add_after, but when I use this method below to get the quantity in stock I just can get the configurable product stock quantity, my simple product is working though.

$quoteItem = $observer->getEvent()->getQuoteItem();
$product = $quoteItem->getProduct();
$typeId = $product->getTypeId();

$productStockData = $product->getExtensionAttributes()->getStockItem(); 

$productQty = (int) $productStockData->getQty();

$message = __(
   '%1 may require a lead time.',
    $product->getName()
);
if ($product->getManageStock() && $productQty <= 0) {
    $this->messageManager->addWarningMessage($message);
}
0

First add the this in your construct:

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

In my case, I created a method to use it:

public function getStockItem($productId){
    return $this->_stockRegistry->getStockItem($productId);
}

Then, you can use the method getCustomOption to get when it’s a configured product:

    $quoteItem = $observer->getEvent()->getQuoteItem();
    $product = $quoteItem->getProduct();
    $typeId = $product->getTypeId();

    if ($typeId == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) {
        $simpleProductSelected = $product->getCustomOption('simple_product')->getProductId();
        $productStockData = $this->getStockItem($simpleProductSelected);
    } else {
        $productStockData = $product->getExtensionAttributes()->getStockItem();
    }

    $productQty = (int) $productStockData->getQty();

    $message = __(
        '%1 may require a lead time.',
        $product->getName()
    );
    if ($this->stockMessaging->isEnable()) {
        $outOfStockQty = (int) $this->stockMessaging->getOutOfStockNumber($product);
        if ($productQty <= $outOfStockQty) {
            $this->messageManager->addWarningMessage($message);
        }
    } elseif ($product->getManageStock() && $productQty <= 0) {
        $this->messageManager->addWarningMessage($message);
    }

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.