Can't getStockItem magento 2.3.1
-
08-03-2021 - |
Pergunta
Block
namespace Vendor\Extension\Block\Product;
use Magento\Framework\View\Element\Template;
class Stickycart extends Template
{
protected $_registry;
protected $_stockItemRepository;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
\Magento\CatalogInventory\Model\Stock\StockItemRepository $stockItemRepository,
array $data = []
) {
$this->_registry = $registry;
$this->_stockItemRepository = $stockItemRepository;
parent::__construct($context, $data);
}
public function getCurrentProduct()
{
return $this->_registry->registry('current_product');
}
public function getStockItem($productId)
{
return $this->_stockItemRepository->get($productId);
}
}
Template
$currentProduct = $block->getCurrentProduct();
$id = $currentProduct->getId();
$_productStock = $block->getStockItem($id);
if($_productStock->getIsInStock()){
...
}
But it show a bug:
The stock item with the "140" ID wasn't found. Verify the ID and try again.
I have checked that product in backend in Catalog but it's instock with qty is 465.
Solução
Try using this \Magento\CatalogInventory\Model\Stock\StockItemRepository
Update your code with following code
namespace Vendor\Extension\Block\Product;
use Magento\Framework\View\Element\Template;
class Stickycart extends Template
{
protected $_registry;
protected $stockRegistry;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
\Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
array $data = []
) {
$this->_registry = $registry;
$this->stockRegistry = $stockRegistry;
parent::__construct($context, $data);
}
public function getCurrentProduct()
{
return $this->_registry->registry('current_product');
}
public function getStockItem($productId)
{
return $this->stockRegistry->getStockItem($productId);
}
}
Hope it Helps.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a magento.stackexchange