0

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.

1 Answer 1

2

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());
3

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.