2

I am creating a module that show the product stock item dynamically, but it is giving error

"Parse error: syntax error, unexpected ':', expecting ')' in C:\xampp\htdocs\magento2.3.3\app\code\Test\Module\Block\StockLeft.php on line 31"

StockLeft.php

<?php 

namespace Test\Module\Block;


use Magento\Framework\Registry;
use Magento\Framework\View\Element\Template;

class StockLeft extends Template
{
    private $registry;

    public function __construct(
        Template\Context $context,
        Registry $registry,
        array $data = [])
    {
        parent::__construct($context, $data);
        $this->registry = $registry;
    }

    public function getRemainingQty(){
        $product = $this->getCurrentProduct();
        return $product->getQty();
    }

    protected function getCurrentProduct(){
        return $this->_registry->registry('product');
    }
}
?>

Template : stockleft.phtml

<?php
    echo $block->getRemainingQty()
?>

Layout : catalog_product_view.xml

<?xml version="1.0"?>
<page layout = "1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <body>
        <referenceContainer name="product.info.stock.sku"> 
            <block class="Test\Module\Block\StockLeft" name="productleft" template="Test_Module::stock_left.phtml"/>
        </referenceContainer>
    </body>
</page>
vinaysirige
  • 105
  • 11

1 Answers1

2

Please update your file with this content

<?php 

namespace Test\Module\Block;


use Magento\Framework\Registry;
use \Magento\Framework\View\Element\Template;

class StockLeft extends Template
{
    private $registry;

    public function __construct(
        Template\Context $context,
        Registry $registry,
        array $data = [])
    {
        parent::__construct($context, $data);
        $this->registry = $registry;
    }

    public function getRemainingQty(){
        $product = $this->getCurrentProduct();
        $stockItem = $product->getExtensionAttributes()->getStockItem();
        return $stockItem->getQty();
    }

    protected function getCurrentProduct(){
        return $this->registry->registry('product');
    }
}
?>

You've added some extra text here in line no : 31 in your code. You can compare below lines..

return $this->registry->registry(key: 'product');

replace this with

return $this->registry->registry('product');

Here key: is not require in your code.

Hope this helps you!

Kishan Savaliya
  • 7,736
  • 1
  • 12
  • 27