By default, Magento only shows stock status. In this tutorial, we will show you how to show stock quantity on product page on Magento 2.
You can get the final package for this feature at the end of this post.
List of files we will create:
- app/code/Metagento/StockQty/view/frontend/layout/catalog_product_view.xml
- app/code/Metagento/StockQty/Block/Catalog/Product/View.php
- app/code/Metagento/StockQty/view/frontend/templates/catalog/product/view.phtml
- app/code/Metagento/StockQty/etc/frontend/routes.xml
- app/code/Metagento/StockQty/Controller/Index/Index.php
Layout file
app/code/Metagento/StockQty/view/frontend/layout/catalog_product_view.xml
1 2 3 4 5 6 7 8 9 10 11 12 |
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="content"> <block class="Metagento\StockQty\Block\Catalog\Product\View" name="product.view.stockqty" template="Metagento_StockQty::catalog/product/view.phtml"/> </referenceBlock> </body> </page> |
Block file
app/code/Metagento/StockQty/Block/Catalog/Product/View.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<?php namespace Metagento\StockQty\Block\Catalog\Product; class View extends \Magento\Framework\View\Element\Template { /** * @var \Magento\Framework\Registry */ protected $registry; /** * @var \Metagento\StockQty\Helper\Config */ protected $helperConfig; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Metagento\StockQty\Helper\Config $helperConfig, \Magento\Framework\Registry $registry, array $data = [] ) { $this->registry = $registry; $this->helperConfig = $helperConfig; parent::__construct($context, $data); } /** * @return \Metagento\StockQty\Helper\Config */ public function getHelperConfig() { return $this->helperConfig; } /** * @return \Magento\Catalog\Model\Product */ public function getProduct() { return $this->registry->registry('product'); } } |
Template file
app/code/Metagento/StockQty/view/frontend/templates/catalog/product/view.phtml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
<?php /** * @var $block \Metagento\StockQty\Block\Catalog\Product\View */ ?> <?php if ($block->getHelperConfig()->isEnabled()): ?> <script type="text/javascript"> requirejs(['jquery', 'underscore'], function (jQuery, _) { var selectedProduct = function () { var selected_options = {}; jQuery('div.swatch-attribute').each(function (k, v) { var attribute_id = jQuery(v).attr('attribute-id'); var option_selected = jQuery(v).attr('option-selected'); //console.log(attribute_id, option_selected); if (!attribute_id || !option_selected) { return; } selected_options[attribute_id] = option_selected; }); var product_id_index = jQuery('[data-role=swatch-options]').data('mageSwatchRenderer').options.jsonConfig.index; var found_ids = []; jQuery.each(product_id_index, function (product_id, attributes) { var productIsSelected = function (attributes, selected_options) { return _.isEqual(attributes, selected_options); } if (productIsSelected(attributes, selected_options)) { found_ids.push(product_id); } }); return found_ids[0]; }; // configurable product jQuery(document).on('click', '.swatch-option', function () { jQuery('.product-info-stock-sku .stock .stock-qty').remove(); var selectedProductId = selectedProduct(); if (selectedProductId > 0) { jQuery.ajax({ method: 'POST', url: '<?php echo $block->getUrl('stockqty/') ?>', data: { product_id: selectedProductId }, beforeSend: function () { }, success: function (response) { var content = response.content; jQuery('.product-info-stock-sku .stock').append("<span class='stock-qty'>" + content + "</span>"); } }); } }); // normal product <?php if($block->getProduct() && $block->getProduct()->getTypeId() == 'simple'): ?> jQuery(document).ready(function () { var selectedProductId = jQuery('#product_addtocart_form input[name=product]').val(); jQuery.ajax({ method: 'POST', url: '<?php echo $block->getUrl('stockqty/') ?>', data: { product_id: selectedProductId }, beforeSend: function () { }, success: function (response) { var content = response.content; jQuery('.product-info-stock-sku .stock').append("<span class='stock-qty'>" + content + "</span>"); } }); }); <?php endif; ?> }); </script> <style> .product-info-stock-sku .stock .stock-qty { margin-left: 17px; } </style> <?php endif; ?> |
Route file
app/code/Metagento/StockQty/etc/frontend/routes.xml
1 2 3 4 5 6 7 8 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> <router id="standard"> <route id="stockqty" frontName="stockqty"> <module name="Metagento_StockQty" /> </route> </router> </config> |
Controller
app/code/Metagento/StockQty/Controller/Index/Index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?php namespace Metagento\StockQty\Controller\Index; class Index extends \Magento\Framework\App\Action\Action { public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\CatalogInventory\Api\StockStateInterface $stockState ) { parent::__construct($context); $this->stockState = $stockState; } /** * Execute action based on request and return result * * Note: Request will be added as operation argument in future * * @return \Magento\Framework\Controller\ResultInterface|\Magento\Framework\App\ResponseInterface * @throws \Magento\Framework\Exception\NotFoundException */ public function execute() { $html = ''; $productId = $this->getRequest()->getParam('product_id'); if ($productId) { $stockQty = $this->stockState->getStockQty($productId); $html = __("Qty: ") . $stockQty; } /** @var \Magento\Framework\Controller\Result\Json $result */ $result = $this->resultFactory->create('json'); return $result->setData(['content' => $html]); } } |
After creating above files, clear magento cache to see the change.
Result
- Simple product page
- Configurable product page
That’s how to show stock quantity on product page, hope this small feature will be helpful.
You can get this module on Github: https://github.com/metagento/magento-2-stock-qty
If you have any question or need any assistance, leave us a message.