Question

I am able to get a product collection by using the ProductRepositoryInterface:

\Magento\Catalog\Api\ProductRepositoryInterface

Then loop through products by doing:

$list = $this->_productRepository->getList($searchCriteria);
$items = $list->getItems();
foreach ($items as $item) {

}

I need to get 'qty' and 'special price' from each $item (product). But $item does not provide these methods:

enter image description here

enter image description here

As you can see $item is a ProductInterface. And in 'vendor\magento\module-catalog\etc\di.xml' there is this line:

<preference for="Magento\Catalog\Api\Data\ProductInterface" type="Magento\Catalog\Model\Product" />

So when I call $item->getQty; or $item->getSpecialPrice(); I should get the corresponding values, because both methods are implemented in Magento\Catalog\Model\Product. But this does not work.

In my Block Class I do:

 $this->setItems($items);

In my phtml file I do:

$items = $this->getItems();
if(!empty($items)){
    foreach ($items as $item) {
        echo "<p> id: ".$item->getId().", name: "
        .$item->getName().", sku: "
        .$item->getSku().", price: ".$item->getPrice()
        .", typeId: ".$item->getTypeId()
        .", visibility: ".$item->getVisibility()
        .", status: ".$item->getStatus()
        .", QTY : ".$item->getQty()
        .", special price: ".$item->getSpecialPrice();
    }
}

Everything works, I get all values except for 'getQty()' and 'getSpecialPrice()'.

I absolutely need 'qty' and 'special price' from each product in the collection.

Can someone help ?

EDIT: @Manthan Dave : I did the following, but got an error because getExtensionAttributes()->getStockItem() returns NULL:

enter image description here

Info: the cache was cleared/flushed multiple times.

Was it helpful?

Solution

Its because of Qty and Special Price both are external attributes of product,so if you directly called via $item then you will not get the value for the same

Try below code :

You can get Qty or other values like min qty by using that method.

echo $item->getExtensionAttributes()->getStockItem()->getQty();

OR Complete Object Data

print_r($item->getExtensionAttributes()->getStockItem()->getData());

clear the cache and check it will works.

Update :

Load stock interface , try below code :

 public function __construct(
    \Magento\CatalogInventory\Api\StockStateInterface $stockItem
   )
  {
    $this->stockItem = $stockItem;
  }

 $this->stockItem->getStockQty($product->getId(), $product->getStore()->getWebsiteId());
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top