0

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.

2

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.

  • It work fine. Thank you! – David Duong Jul 25 '19 at 11:48
  • 1
    glad it worked. – Mohit Rane Jul 25 '19 at 11:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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