I'm trying to get the stock quantity of an item in the cart in Magento CE 2.2.5. To do so, I'm injecting \Magento\CatalogInventory\Api\StockRegistryInterface into \Magento\Checkout\Block\Cart\Item\Renderer so I can create a function that will get the quantity of an item.
However, any function created in this custom module simply does return any data to the frontend. If I create a function like
public function testReturn() {
return 'Test!';
}and try to echo it in the cart by using
<?= $block->testReturn(); ?>
nothing at all is displayed. I've cleared the cache, run bin/magento setup:di:compile, and rebooted the dev server. Any idea on where I'm going wrong? Full code follows below.
<?php
namespace Vendor\Module\Block\Cart\Item;
use Magento\Catalog\Pricing\Price\ConfiguredPriceInterface;
use Magento\Checkout\Block\Cart\Item\Renderer\Actions;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Framework\View\Element\AbstractBlock;
use Magento\Framework\View\Element\Message\InterpretationStrategyInterface;
use Magento\Quote\Model\Quote\Item\AbstractItem;
class Renderer extends \Magento\Checkout\Block\Cart\Item\Renderer
{
/**
* @var \Magento\Checkout\Model\Session
*/
protected $_checkoutSession;
/**
* @var AbstractItem
*/
protected $_item;
/**
* @var string
*/
protected $_productUrl;
/**
* Whether qty will be converted to number
*
* @var bool
*/
protected $_strictQtyMode = true;
/**
* Check, whether product URL rendering should be ignored
*
* @var bool
*/
protected $_ignoreProductUrl = false;
/**
* Catalog product configuration
*
* @var \Magento\Catalog\Helper\Product\Configuration
*/
protected $_productConfig = null;
/**
* @var \Magento\Framework\Url\Helper\Data
*/
protected $_urlHelper;
/**
* @var \Magento\Framework\Message\ManagerInterface
*/
protected $messageManager;
/**
* @var \Magento\Catalog\Block\Product\ImageBuilder
*/
protected $imageBuilder;
/**
* @var PriceCurrencyInterface
*/
protected $priceCurrency;
/**
* @var \Magento\Framework\Module\Manager
*/
public $moduleManager;
/**
* @var InterpretationStrategyInterface
*/
private $messageInterpretationStrategy;
/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Catalog\Helper\Product\Configuration $productConfig
* @param \Magento\Checkout\Model\Session $checkoutSession
* @param \Magento\Catalog\Block\Product\ImageBuilder $imageBuilder
* @param \Magento\Framework\Url\Helper\Data $urlHelper
* @param \Magento\Framework\Message\ManagerInterface $messageManager
* @param PriceCurrencyInterface $priceCurrency
* @param \Magento\Framework\Module\Manager $moduleManager
* @param InterpretationStrategyInterface $messageInterpretationStrategy
* @param array $data
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
* @codeCoverageIgnore
*/
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,
\Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
array $data = []
) {
$this->stockRegistry = $stockRegistry;
parent::__construct($context, $productConfig, $checkoutSession, $imageBuilder, $urlHelper, $messageManager, $priceCurrency, $moduleManager, $messageInterpretationStrategy, $data);
}
public function getItemStockQty() {
return $this->stockRegistry->getStockItem($this->_item->getProduct->getId(), $this->_item->getStoreId())->getQty();
}
}
Solved! Go to Solution.
Why you have not override, Its such a intrigue but you can also do using other way like below way,
Create Helper file,
Define your custom function, Call Custom function from helper by calling,
$helper = $this->helper('Vendor/Module/Helper/Data');
echo $helper->getItemStockQty();
Hi @phabeeb
I think you are missing di.xml file over here ! where you need to give preference by using preference tag to execute your model instead of core model of Magento !
Correct me if you have created di.xml file - then post it over here , so its help us troubleshoot the issue !
Here's my di.xml file:
<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\Block\Cart\Item\Renderer" /> <type name="Magento\ConfigurableProduct\Block\Product\View\Type\Configurable"> <plugin name="Vendor_configurable_product_configurable" type="Vendor\Module\Block\ConfigurableProduct\Product\View\Type\Configurable" /> </type> </config>
Hi @phabeeb
Well looking at the code it sounds like ok !
Still refer this link - https://magento.stackexchange.com/questions/112858/magento2-custom-module-overrides-layout-the-eleme...
Not sure but this might help you !
Thanks for the link, @Manthan Dave. That information does let me override cart/item/default.phtml, but weirdly I'm still not seeing anything from my custom functions.
Hello phabeeb
If you want override "cart/item/default.phtml"
app\code\Vendor\Module\Block\Cart\AbstractCart.php
<?php
/**
* Override cart item block in custom module
*/
namespace Vendor\Custom\Block\Cart;
class AbstractCart
{
public function afterGetItemRenderer(\Magento\Checkout\Block\Cart\AbstractCart $subject, $result)
{
$result->setTemplate('Vendor_Custom::cart/item/default.phtml');
return $result;
}
}
app\code\Vendor\Module\etc\di.xml
<type name="Magento\Checkout\Block\Cart\AbstractCart">
<plugin name="cart-item-override" type="Vendor\Custom\Block\Cart\AbstractCart" sortOrder="1"/>
</type>app\code\Vendor\Custom\view\frontend\cart\item\default.phtml
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
/** @var $block \Magento\Checkout\Block\Cart\Item\Renderer */
die('template overridden');
$_item = $block->getItem();
$product = $_item->getProduct();
$isVisibleProduct = $product->isVisibleInSiteVisibility();
/** @var \Magento\Msrp\Helper\Data $helper */
$helper = $this->helper('Magento\Msrp\Helper\Data');
$canApplyMsrp = $helper->isShowBeforeOrderConfirm($product) && $helper->isMinimalPriceLessMsrp($product);
?>
<tbody class="cart item">
<tr class="item-info">
<td data-th="<?= $block->escapeHtml(__('Item')) ?>" class="col item">
<?php if ($block->hasProductUrl()):?>
<a href="<?= /* @escapeNotVerified */ $block->getProductUrl() ?>"
title="<?= $block->escapeHtml($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="<?= /* @escapeNotVerified */ $block->getProductUrl() ?>"><?= $block->escapeHtml($block->getProductName()) ?></a>
<?php else: ?>
<?= $block->escapeHtml($block->getProductName()) ?>
<?php endif; ?>
</strong>
<p><strong>Note: </strong>This is a renewal prodcut.</p>
<?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'])): ?>
<?= /* @escapeNotVerified */ $_formatedOptionValue['full_view'] ?>
<?php else: ?>
<?= /* @escapeNotVerified */ $_formatedOptionValue['value'] ?>
<?php endif; ?>
</dd>
<?php endforeach; ?>
</dl>
<?php endif;?>
<?php if ($messages = $block->getMessages()): ?>
<?php foreach ($messages as $message): ?>
<div class="cart item message <?= /* @escapeNotVerified */ $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->escapeHtml(__('Price')) ?>">
<span class="pricing msrp">
<span class="msrp notice"><?= /* @escapeNotVerified */ __('See price before order confirmation.') ?></span>
<?php $helpLinkId = 'cart-msrp-help-' . $_item->getId(); ?>
<a href="#" class="action help map" id="<?= /* @escapeNotVerified */ ($helpLinkId) ?>" data-mage-init='{"addToCart":{"helpLinkId": "#<?= /* @escapeNotVerified */ $helpLinkId ?>","productName": "<?= /* @escapeNotVerified */ $product->getName() ?>","showAddToCart": false}}'>
<span><?= /* @escapeNotVerified */ __("What's this?") ?></span>
</a>
</span>
</td>
<?php else: ?>
<td class="col price" data-th="<?= $block->escapeHtml(__('Price')) ?>">
<?= $block->getUnitPriceHtml($_item) ?>
</td>
<?php endif; ?>
<td class="col qty" data-th="<?= $block->escapeHtml(__('Qty')) ?>">
<div class="field qty">
<label class="label" for="cart-<?= /* @escapeNotVerified */ $_item->getId() ?>-qty">
<span><?= /* @escapeNotVerified */ __('Qty') ?></span>
</label>
<div class="control qty">
<input id="cart-<?= /* @escapeNotVerified */ $_item->getId() ?>-qty"
name="cart[<?= /* @escapeNotVerified */ $_item->getId() ?>][qty]"
data-cart-item-id="<?= /* @escapeNotVerified */ $_item->getSku() ?>"
value="<?= /* @escapeNotVerified */ $block->getQty() ?>"
type="number"
size="4"
title="<?= $block->escapeHtml(__('Qty')) ?>"
class="input-text qty"
data-validate="{required:true,'validate-greater-than-zero':true}"
data-role="cart-item-qty"/>
</div>
</div>
</td>
<td class="col subtotal" data-th="<?= $block->escapeHtml(__('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="100">
<div class="actions-toolbar">
<?= /* @escapeNotVerified */ $block->getActions($_item) ?>
</div>
</td>
</tr>
</tbody>
Hope it will help you to sove problem then accept as solution
Check override default.phtml file using below way,https://www.rakeshjesadiya.com/how-to-override-cart-item-default-phtml-in-magento-2/
Hi @Rakesh Jesadiya and @prakash786,
Thanks for the information. I was able to override the block after using information from @Manthan Dave's link, but my custom function still does not display any information in the cart area, despite having successfully overridden the block. If I try something like
<?= $block->escapeHtml(__('Test echo')) ?>in my custom default.phtml, it will appear in the cart. But if I try
<?= $block->getItemStockQty() ?>
which is the function I'm trying to create, nothing appears, even if then entire contents of getItemStockQty() is something like:
public function getItemStockQty() {
return '12345';
} Any thoughts?
Why you have not override, Its such a intrigue but you can also do using other way like below way,
Create Helper file,
Define your custom function, Call Custom function from helper by calling,
$helper = $this->helper('Vendor/Module/Helper/Data');
echo $helper->getItemStockQty();
Thanks, @Rakesh Jesadiya. That did the trick.