2

How to check checkout cart page stock status in magento 2.3

my custom code add this file but not working

             <?php if ($product->isAvailable()): ?>
                <div class="stock available" title="<?php /* @escapeNotVerified */ echo __('Availability') ?>">
                    <i class="fa fa-check-circle" aria-hidden="true"></i>
                    <span><?php /* @escapeNotVerified */ echo __('In Stock') ?></span>
                </div>
            <?php else: ?>
                <div class="stock unavailable" title="<?php /* @escapeNotVerified */ echo __('Availability') ?>">
                    <span><?php /* @escapeNotVerified */ echo __('Out of Stock') ?></span>
                </div>
            <?php endif; ?>

app/design/frontend/Themename/Magento_checkout/templates/cart/item/default.phtml

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// phpcs:disable Magento2.Templates.ThisInTemplate
// phpcs:disable Magento2.Files.LineLength.MaxExceeded

/** @var $block \Magento\Checkout\Block\Cart\Item\Renderer */

$_item = $block->getItem();
$product = $_item->getProduct();
$isVisibleProduct = $product->isVisibleInSiteVisibility();
/** @var \Magento\Msrp\Helper\Data $helper */
$helper = $this->helper(Magento\Msrp\Helper\Data::class);
$canApplyMsrp = $helper->isShowBeforeOrderConfirm($product) && $helper->isMinimalPriceLessMsrp($product);
?>
<tbody class="cart item">
    <tr class="item-info">
        <td data-th="<?= $block->escapeHtmlAttr(__('Item')) ?>" class="col item">
            <?php if ($block->hasProductUrl()) :?>
                <a href="<?= $block->escapeUrl($block->getProductUrl()) ?>"
                   title="<?= $block->escapeHtmlAttr($block->getProductName()) ?>"
                   tabindex="-1"
                   class="product-item-photo">
            <?php else :?>
                <span class="product-item-photo">
            <?php endif;?>
            <?= $block->getImage($block->getProductForThumbnail(), 'cart_page_product_thumbnail')->toHtml() ?>
            <?php if ($block->hasProductUrl()) :?>
                </a>
            <?php else :?>
                </span>
            <?php endif; ?>
            <div class="product-item-details">
                <strong class="product-item-name">
                    <?php if ($block->hasProductUrl()) :?>
                        <a href="<?= $block->escapeUrl($block->getProductUrl()) ?>"><?= $block->escapeHtml($block->getProductName()) ?></a>
                    <?php else :?>
                        <?= $block->escapeHtml($block->getProductName()) ?>
                    <?php endif; ?>
                </strong>
                <?php if ($_options = $block->getOptionList()) :?>
                    <dl class="item-options">
                        <?php foreach ($_options as $_option) :?>
                            <?php $_formatedOptionValue = $block->getFormatedOptionValue($_option) ?>
                            <dt><?= $block->escapeHtml($_option['label']) ?></dt>
                            <dd>
                                <?php if (isset($_formatedOptionValue['full_view'])) :?>
                                    <?= $block->escapeHtml($_formatedOptionValue['full_view']) ?>
                                <?php else :?>
                                    <?= $block->escapeHtml($_formatedOptionValue['value'], ['span', 'a']) ?>
                                <?php endif; ?>
                            </dd>
                        <?php endforeach; ?>
                    </dl>
                <?php endif;?>
                <?php if ($messages = $block->getMessages()) :?>
                    <?php foreach ($messages as $message) :?>
                        <div class= "cart item message <?= $block->escapeHtmlAttr($message['type']) ?>">
                            <div><?= $block->escapeHtml($message['text']) ?></div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
                <?php $addInfoBlock = $block->getProductAdditionalInformationBlock(); ?>
                <?php if ($addInfoBlock) :?>
                    <?= $addInfoBlock->setItem($_item)->toHtml() ?>
                <?php endif;?>
            </div>
        </td>

        <?php if ($canApplyMsrp) :?>
            <td class="col msrp" data-th="<?= $block->escapeHtmlAttr(__('Price')) ?>">
                <span class="pricing msrp">
                    <span class="msrp notice"><?= $block->escapeHtml(__('See price before order confirmation.')) ?></span>
                    <?php $helpLinkId = 'cart-msrp-help-' . $_item->getId(); ?>
                    <a href="#" class="action help map"
                       id="<?= ($block->escapeHtmlAttr($helpLinkId)) ?>"
                       data-mage-init='{"addToCart":{
                                            "helpLinkId": "#<?= $block->escapeJs($block->escapeHtml($helpLinkId)) ?>",
                                            "productName": "<?= $block->escapeJs($block->escapeHtml($product->getName())) ?>",
                                            "showAddToCart": false
                                            }
                                        }'
                    >
                        <span><?= $block->escapeHtml(__("What's this?")) ?></span>
                    </a>
                </span>
            </td>
        <?php else :?>
            <td class="col price" data-th="<?= $block->escapeHtmlAttr(__('Price')) ?>">
                <?= $block->getUnitPriceHtml($_item) ?>
            </td>
        <?php endif; ?>
        <td class="col qty" data-th="<?= $block->escapeHtmlAttr(__('Qty')) ?>">
            <div class="field qty">
                <div class="control qty">
                    <label for="cart-<?= $block->escapeHtmlAttr($_item->getId()) ?>-qty">
                        <span class="label"><?= $block->escapeHtml(__('Qty')) ?></span>
                        <input id="cart-<?= $block->escapeHtmlAttr($_item->getId()) ?>-qty"
                               name="cart[<?= $block->escapeHtmlAttr($_item->getId()) ?>][qty]"
                               data-cart-item-id="<?= $block->escapeHtmlAttr($_item->getSku()) ?>"
                               value="<?= $block->escapeHtmlAttr($block->getQty()) ?>"
                               type="number"
                               size="4"
                               step="any"
                               title="<?= $block->escapeHtmlAttr(__('Qty')) ?>"
                               class="input-text qty"
                               data-validate="{required:true,'validate-greater-than-zero':true}"
                               data-role="cart-item-qty"/>
                    </label>
                </div>
            </div>
        </td>

        <td class="col subtotal" data-th="<?= $block->escapeHtmlAttr(__('Subtotal')) ?>">
            <?php if ($canApplyMsrp) :?>
                <span class="cart msrp subtotal">--</span>
            <?php else :?>
                <?= $block->getRowTotalHtml($_item) ?>
            <?php endif; ?>
        </td>
    </tr>
    <tr class="item-actions">
        <td colspan="4">
            <div class="actions-toolbar">
                <?= /* @noEscape */ $block->getActions($_item) ?>
            </div>
        </td>
    </tr>
</tbody>

1 Answer 1

2

app/code/Vendor/Module/etc/di.xml

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Checkout\Block\Cart\Item\Renderer" type="Vendor\Module\Plugin\Checkout\Block\Cart\Item\Renderer" />

app/code/Vendor/Module/registration.php

<?php

use \Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Vendor_Module', __DIR__);

app/code/Vendor/Module/etc/module.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Vendor_Module">
    <sequence>
        <module name="Magento_Checkout"/>
    </sequence>
</module>

app/code/Vendor/Module/Plugin/Checkout/Block/Cart/Item/Renderer.php

<?php
 namespace Vendor\Module\Plugin\Checkout\Block\Cart\Item;

 use Magento\Catalog\Model\Product\Configuration\Item\ItemResolverInterface;
 use Magento\CatalogInventory\Helper\Data;
 use Magento\CatalogInventory\Model\Stock;
 use Magento\Framework\Pricing\PriceCurrencyInterface;
 use Magento\Framework\View\Element\Message\InterpretationStrategyInterface;

 class Renderer extends \Magento\Checkout\Block\Cart\Item\Renderer
 {
     protected $stockRegistry;
     public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Helper\Product\Configuration $productConfig,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Catalog\Block\Product\ImageBuilder $imageBuilder,
        \Magento\Framework\Url\Helper\Data $urlHelper,
        \Magento\Framework\Message\ManagerInterface $messageManager,
         PriceCurrencyInterface $priceCurrency, \Magento\Framework\Module\Manager $moduleManager,
         InterpretationStrategyInterface $messageInterpretationStrategy,
         array $data = [],
         ItemResolverInterface $itemResolver = null,
         \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
)
{
    parent::__construct($context, $productConfig, $checkoutSession, $imageBuilder, $urlHelper, $messageManager, $priceCurrency, $moduleManager, $messageInterpretationStrategy, $data, $itemResolver);
    $this->stockRegistry = $stockRegistry;
}

public function isProductAvailable()
{
    $quoteItem = $this->getItem();
    $product = $this->getProduct();
    /* @var \Magento\CatalogInventory\Api\Data\StockStatusInterface $stockStatus */
    $stockStatus = $this->stockRegistry->getStockStatus($product->getId(), $product->getStore()->getWebsiteId());

    /* @var \Magento\CatalogInventory\Api\Data\StockStatusInterface $parentStockStatus */
    $parentStockStatus = false;

    /**
     * Check if product in stock. For composite products check base (parent) item stock status
     */
    if ($quoteItem->getParentItem()) {
        $product = $quoteItem->getParentItem()->getProduct();
        $parentStockStatus = $this->stockRegistry->getStockStatus(
            $product->getId(),
            $product->getStore()->getWebsiteId()
        );
    }

    if ($stockStatus) {
        if ($stockStatus->getStockStatus() === Stock::STOCK_OUT_OF_STOCK
            || $parentStockStatus && $parentStockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK
        ) {
            return false;
        } else {
            return true;
        }
    }
}
}

app/design/frontend/Themename/Magento_checkout/templates/cart/item/default.phtml

<?php if ($block->isProductAvailable()): ?>
    <div class="stock available  col-lg-4" title="<?php /* @escapeNotVerified */ echo __('Availability') ?>">
        <i class="fa fa-check-circle" aria-hidden="true"></i>
        <span><?php /* @escapeNotVerified */ echo __('In Stock') ?></span>
    </div>
<?php else: ?>
    <div class="stock unavailable  col-lg-4" title="<?php /* @escapeNotVerified */ echo __('Availability') ?>">
        <span><?php /* @escapeNotVerified */ echo __('Out of Stock') ?></span>
    </div>
<?php endif; ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.