Magento 2 how to show configurable options stock availability on product page
addtocart.phtml <?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ // @codingStandardsIgnoreFile /** @var $block \Magento\Catalog\Block\Product\View */ ?> <?php $_product = $block->getProduct(); ?> <?php $buttonTitle = __('Add to Cart'); ?> <?php if ($_product->isSaleable()): ?> <div class="box-tocart"> <div class="fieldset"> <?php if ($block->shouldRenderQuantity()): $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');?> <div class="field qty"> <label class="label" for="qty"><span><?= /* @escapeNotVerified */ __('Qty') ?></span></label> <div class="control"> <?php if($_product->getTypeId()=="simple") { ?> <select class="input-text qty" name="qty" id="qty" data-validate="<?= $block->escapeHtml(json_encode($block->getQuantityValidators())) ?>"> <?php $availableQty= $StockState->getStockQty($_product->getId(), $_product->getStore()->getWebsiteId()); for($repli=1;$repli<=$availableQty;$repli++) echo "<option value='$repli'>$repli</option>"; ?> </select> <?php } else { $usedProducts = $_product->getTypeInstance()->getUsedProducts($_product); $productStockd=$objectManager->get('Magento\CatalogInventory\Api\StockRegistryInterface'); $finalconfigqty=[]; foreach ($usedProducts as $child) {$childid=$child->getId(); $productStockObj = $productStockd->getStockItem($childid); $availableQty= round($productStockObj->getData('qty')); $finalconfigqty['c'.$childid]=$availableQty; } echo '<script> var fichoo='. json_encode($finalconfigqty). '</script>'; echo '<select class="input-text qty fichoo" name="qty" id="qty"><option value=1>1</option></select>'; ?> <!--input type="number" name="qty" id="qty" value="<?= $block->getProductDefaultQty() * 1 ?>" title="<?= __('Qty') ?>" class="input-text qty" data-validate="<?= $block->escapeHtml(json_encode($block->getQuantityValidators())) ?>" /--> <?php } ?> </div> </div> <?php endif; ?> <div class="actions"> <button type="submit" title="<?= /* @escapeNotVerified */ $buttonTitle ?>" class="action primary tocart" id="product-addtocart-button"> <span><?= /* @escapeNotVerified */ $buttonTitle ?></span> </button> <?= $block->getChildHtml('', true) ?> </div> </div> </div> <?php endif; ?> <?php if ($block->isRedirectToCartEnabled()) : ?> <script type="text/x-magento-init"> { "#product_addtocart_form": { "Magento_Catalog/product/view/validation": { "radioCheckboxClosest": ".nested" } } } </script> <?php else : ?> <script type="text/x-magento-init"> { "#product_addtocart_form": { "Magento_Catalog/js/validate-product": {} } } </script> <?php endif; ?> Another important file is Magento_ConfigurableProduct/web/js/configurable.js ...