How to check if a product is salable using isSalable()?
Question
I am trying to use plugin to override Magento\Checkout\Model\Cart.php
- addOrderItem function
Instead of getting item's quantity, how to check if product is salable using isSalable()? Is there any way to use product id to get if product is isSalable().
public function aroundAddOrderItem($subject, callable $proceed, $orderItem, $qtyFlag = null)
{
if ($orderItem->getParentItem() === null) {
$sku = $orderItem->getSku();
$productId=$this->product->getIdBySku($sku);
$productStock = $this->stockItemRepository->get($productId);
$productQty = $productStock->getQty();
if($productQty < 1)
{
return $this;
}
else
{
return $proceed($orderItem, $qtyFlag);
}
}
return $this;
}
Solution
You can check product is isSalable by below code using SKU.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$sku = $orderItem->getSku();
$salable = $objectManager->create('Magento\InventorySalesAdminUi\Model\GetSalableQuantityDataBySku')->execute($sku);
foreach ($salable as $key => $value) {
$salableQty = $value['qty'];
}
You should not use the ObjectManager directly!
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange