Magento 2.2.3 – How to Get Stock Data in Product Listing via afterGetList Plugin

event-observermagento2magento2.2.3plugin

Since magento 2.2.3 is displaying out of stock items in product listing, I would like to get the qty attribute in the listing using rest API. I'm using afterGetList plugin.

di.xml

<type name="Magento\Catalog\Api\ProductRepositoryInterface">
    <plugin name="get_product_metrics" type="Custom\Module\Plugin\ProductGet"/>
</type>

Custom/Module/etc/extension_attributes.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
    <extension_attributes for="Magento\Catalog\Api\Data\ProductInterface">
        <attribute code="qty" type="string"/>
    </extension_attributes>
</config>

ProductGet.php

 <?php

namespace Custom\Module\Plugin;

use Magento\Catalog\Api\Data\ProductInterface;

class ProductGet{
protected $productExtensionFactory;
protected $productFactory;

public function __construct(
    \Magento\Catalog\Api\Data\ProductExtensionFactory $productExtensionFactory,
    \Magento\Catalog\Model\ProductFactory $productFactory,
    \Magento\CatalogInventory\Api\StockStateInterface $stockItem,
    \Psr\Log\LoggerInterface $logger,
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface $mediaGallery,
    \Magento\Eav\Model\Config $eavConfig
)
{
    $this->productFactory = $productFactory;
    $this->storeManager = $storeManager;
    $this->logger = $logger;
    $this->stockItem = $stockItem;
    $this->productExtensionFactory = $productExtensionFactory;
    $this->eavConfig = $eavConfig;
    $this->mediaGallery = $mediaGallery;
}

public function afterGet(
    \Magento\Catalog\Api\ProductRepositoryInterface $subject,
    \Magento\Catalog\Api\Data\ProductInterface $product){

    $this->logger->info("Inside AfterGet ");

    $imageUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

    if($product->getImage()){
        $product->setCustomAttribute("image", $imageUrl.'catalog/product'.$product->getImage());
    }

    return $product;
}


/**
 * @param \Magento\Catalog\Api\ProductRepositoryInterface $subject
 * @param \Magento\Catalog\Model\ResourceModel\Product\Collection $products
 * @return \Magento\Catalog\Model\ResourceModel\Product\Collection
 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
 */
    public function afterGetList(
    \Magento\Catalog\Api\ProductRepositoryInterface $subject,
    $products
    )
    {
        $this->logger->info("list: ".json_encode($products->getItems()));
        /** @var  $product */
        foreach ($products->getItems() as $key => $product) {
            $qty = $this->stockItem->getStockQty($product->getId(), $product->getStore()->getWebsiteId());
            $extensionattributes = $product->getExtensionAttributes();
            $extensionattributes->setQty($qty);
            $product->setExtensionAttributes($extensionattributes);
        }
        return $products;
    }
}

Can anyone help on this? Thanks in advance!

Best Answer

you can add qty attribute using extension_attributes.xml. Here is the code for that

create extension_attributes.xml in etc/ folder of your module.

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">

<extension_attributes for="Magento\Catalog\Api\Data\ProductInterface">
    <attribute code="qty" type="string"/>
</extension_attributes>

and add this code in your afterGetList()

public function afterGetList(
    \Magento\Catalog\Api\ProductRepositoryInterface $subject,
    $products
) {
    foreach ($products->getItems() as $key => $product) {
        $qty = $this->stockItem->getStockQty($product->getId(), $product->getStore()->getWebsiteId());
        $extensionattributes = $product->getExtensionAttributes();
        $extensionattributes->setQty($qty);
        $product->setExtensionAttributes($extensionattributes);
    }
    return $products;
}

You can get more idea from here https://devdocs.magento.com/guides/v2.2/extension-dev-guide/extension_attributes/adding-attributes.html

Hope it will help you.