0

I need help for Magento 2.x. Recently I have developed a eCommerce site. On products details page has "Stock Availability" using "In Stock" status.

So, I want to show the total number of quantity "like Stock: 20" instead of "In Stock" Status.

Could anyone please help to do that in my Magento 2.x eCommerce website.

Please check my attached images below then you can get the clear idea about my words what i have mentioned in above?

Please tell me where I have to write the code to get total quantity number Like "Stock: 20" enter image description here

Thanks in Advance

Ben

0

Add below code in your helper or block to get product QTY.

protected $stockItem;

public function __construct(
    \Magento\Framework\App\Helper\Context $context,
    \Magento\CatalogInventory\Api\StockStateInterface $stockItem
) {
    $this->stockItem = $stockItem;
    parent::__construct($context);
}

public function getStockQty(ModelProduct $product)
{
    $qty = $this->stockItem->getStockQty($product->getId(), $product->getStore()->getWebsiteId());
    return $qty;
}

Inside Product View page

$helper = $this->helper('Namespace\Module\Helper\Data'); 
$qty = $helper->getStockQty($product); // Pass $product object

Hope it helps :)

0

Create a helper class


namespace VendorName\StackExchange\Helper;


class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    /**
     * @var \Magento\CatalogInventory\Api\StockRegistryInterface
     */
    protected $stockRegistry;

    /**
     * Data constructor.
     * 
     * @param \Magento\Framework\App\Helper\Context $context
     * @param \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
     */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
    ) {
        $this->stockRegistry = $stockRegistry;
        parent::__construct($context);
    }

    public function getStockQty($product)
    {
        return $this->stockRegistry->getStockStatus($product->getId(), $product->getStore()->getWebsiteId())->getQty();
    }
}

And now Overwrite following template Magento/Catalog/view/frontend/templates/product/view/type/default.phtml

And add following code


<?php echo $this->helper('VendorName\StackExchange\Helper\Data')->getStockQty($_product);?>

Clear cache.

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.