1

I will try get total stock product qty.

I use this below code:

    <?php
echo "Total qty: ";
?>
<?php 
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
    echo $StockState->getStockQty($productId);
?>

But script display 0 qty for all products.

Here is full file code:

<?php
$_helper = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Catalog\Helper\Output');
$_product = $this->getProduct();
$options = $_product->getOptions();
$matrix = $this->getPriceMatrix(2);
/*
 * border="0" cellspacing="0" cellpadding="0"
 */
?>
<?php if ($matrix && is_array($matrix)) : ?>
       <h4 class="product name product-item-name">
                                                <?php 
                            $optionText = '';
                            $attr = $_product->getResource()->getAttribute('mgs_brand');
                            if ($attr->usesSource()) {
                               $optionText = $attr->getSource()->getOptionText($_product->getMgsBrand());
                            }
                        ?>
                        <?php if($optionText){ ?>
                            <div class="brand-name"><?php echo $optionText ?></div>
                        <?php } ?>
                            </h4><br />
    <table style="width:100%">
        <tbody>
        <?php foreach ($matrix as $r => $variant) : ?>
            <tr class="<?php echo ($r % 2) == 0 ? 'odd' : 'even'; ?>">
                <td style="text-align:left;width:50%">
                    <?php $i = 0;
                    foreach ($variant['attributes'] as $attribute => $variants) :$i++ ?>
                        <?php if ($i > 1) : ?><br/><?php endif; ?>
                        <span class="label"><?php echo $attribute; ?><span>: </span></span>
                        <span class="data"><?php $idx = 0;
                            foreach ($variants as $name => $tmp) : ?><?php echo $idx++ ? ',' : ''; ?><?php echo $name; ?><?php endforeach; ?></span>
                    <?php endforeach; ?>
                </td>
                <td style="text-align:right;width:30%">
                    <div class="bl-price-variants"><?php echo $variant['price_formated']; ?></div>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <?php
echo "Total qty: ";
?>
<?php 
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
    echo $StockState->getStockQty($productId);
?>
    <hr />
<?php endif; ?>

update2:

I created file in: app/code/Snmportal/Publication/Block/stockleft.php

<?php
/**
 * @copyright Devidas
 *
 * @see PROJECT_LICENSE.txt
 */
namespace Snmportal\Publication\Block;

use Magento\Framework\View\Element\Template;
use Magento\Catalog\Model\Product;
use Magento\Framework\View\Element\Template\Context;
use Magento\Framework\Registry;
use Magento\Framework\Session\SessionManagerInterface;
use Magento\CatalogInventory\Api\StockRegistryInterface;
/**
 * Class StockLeft
 */
class StockLeft extends Template
{
    /** @var Registry  */
    private $_registry;

    /** @var Product  */
    private $_Product;

    /** @var session  */
    private $session;

    /** @var session  */
    private $stockRegistry;

    /**
     * StockLeft constructor.
     * @param Context $context
     * @param Registry $registry
     * @param Product $product
     * @param SessionManagerInterface $session
     * @param array $data
     */
    public function __construct(
        Context $context,
        Registry $registry,
        Product $product,
        SessionManagerInterface $session,
        StockRegistryInterface $stockRegistry,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->_registry = $registry;
        $this->_Product = $product;
        $this->session = $session;
        $this->stockRegistry = $stockRegistry;
    }

    /**
     * @return string
     */
    public function getRemainingQty() {
        $productId = $this->getCurrentProduct();
        $stock = $this->stockRegistry->getStockItem($productId);
        return $stock->getQty();
    }

    /**
     * @return Magento\Catalog\Model\Product
     */
    protected function getCurrentProduct() {
        return $this->_registry->registry('current_product')->getId();
    }


}

Next I add code to: app/code/Snmportal/Publication/data/generator/price_variants2.phtml

<?php 
/**
 * @copyright Devidas
 *
 * @see PROJECT_LICENSE.txt
 *
 *@var Snmportal\Publication\Block\StockLeft $block
 **/
$RemainingQty = $block->getRemainingQty();

?>
<?php
$_helper = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Catalog\Helper\Output');
$_product = $this->getProduct();
$options = $_product->getOptions();
$matrix = $this->getPriceMatrix(2);
/*
 * border="0" cellspacing="0" cellpadding="0"
 */
?>
<?php if ($matrix && is_array($matrix)) : ?>
       <h4 class="product name product-item-name">
                                                <?php 
                            $optionText = '';
                            $attr = $_product->getResource()->getAttribute('mgs_brand');
                            if ($attr->usesSource()) {
                               $optionText = $attr->getSource()->getOptionText($_product->getMgsBrand());
                            }
                        ?>
                        <?php if($optionText){ ?>
                            <div class="brand-name"><?php echo $optionText ?></div>
                        <?php } ?>
                            </h4><br />
    <table style="width:100%">
        <tbody>
        <?php foreach ($matrix as $r => $variant) : ?>
            <tr class="<?php echo ($r % 2) == 0 ? 'odd' : 'even'; ?>">
                <td style="text-align:left;width:50%">
                    <?php $i = 0;
                    foreach ($variant['attributes'] as $attribute => $variants) :$i++ ?>
                        <?php if ($i > 1) : ?><br/><?php endif; ?>
                        <span class="label"><?php echo $attribute; ?><span>: </span></span>
                        <span class="data"><?php $idx = 0;
                            foreach ($variants as $name => $tmp) : ?><?php echo $idx++ ? ',' : ''; ?><?php echo $name; ?><?php endforeach; ?></span>
                    <?php endforeach; ?>
                </td>
                <td style="text-align:right;width:30%">
                    <div class="bl-price-variants"><?php echo $variant['price_formated']; ?></div>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <p>Qty Available: <?php echo $RemainingQty; ?></p>
    <hr />
<?php endif; ?>

Now When I try generate catalog pdf then get issue:

Fatal error: Uncaught Error: Call to a member function getRemainingQty() on null in /home/user/domains/domain.com/public_html/app/code/Snmportal/Publication/data/generator/price_variants2.phtml:9 Stack trace: #0 /home/user/domains/domain.com/public_html/var/tmp/snmpdf5e4fd692cebde3.63866984.php(2): include() #1 /home/user/domains/domain.com/public_html/app/code/Snmportal/Publication/Block/Generator.php(327): include('/home/user/d...') #2 /home/user/domains/domain.com/public_html/app/code/Snmportal/Publication/Block/Generator.php(344): Snmportal\Publication\Block\Generator->renderSource('<?php\r\ninclude ...') #3 /home/user/domains/domain.com/public_html/app/code/Snmportal/Publication/Block/Generator.php(303): Snmportal\Publication\Block\Generator->fetchView('dummy') #4 /home/user/domains/domain.com/public_html/vendor/magento/framework/View/Element/AbstractBlock.php(667): Snmportal\Publication\Block\Generator->_toHtml() #5 /home/user/domains/domain.com/public_html/app/code/Snmportal/Publication/Helper/Data in /home/user/domains/domain.com/public_html/app/code/Snmportal/Publication/data/generator/price_variants2.phtml on line 9
12
  • Hello @Sylvester Please follow this links :- magento.stackexchange.com/questions/97943/… Commented Feb 21, 2020 at 4:31
  • the issue is your product id not pass to getCurrentProduct()
    – Devidas
    Commented Feb 21, 2020 at 13:23
  • Do you now how to solve?
    – Sylvester
    Commented Feb 21, 2020 at 13:24
  • yes wait for a min I will update my code
    – Devidas
    Commented Feb 21, 2020 at 13:26
  • First, get product id in your template file. I just get product id using getProductId() function. then replace 2 line below code in your template file $productId = $this->getProductId(); $RemainingQty = $block->getRemainingQty($productId);
    – Devidas
    Commented Feb 21, 2020 at 13:38

2 Answers 2

1

Try below code

create a block for the business logic of template Custom\Modulestock\Block\StockLeft.php

<?php
/**
 * @copyright Devidas
 *
 * @see PROJECT_LICENSE.txt
 */
namespace Custom\Modulestock\Block;

use Magento\Framework\View\Element\Template;
use Magento\Catalog\Model\Product;
use Magento\Framework\View\Element\Template\Context;
use Magento\Framework\Registry;
use Magento\Framework\Session\SessionManagerInterface;
use Magento\CatalogInventory\Api\StockRegistryInterface;
/**
 * Class StockLeft
 */
class StockLeft extends Template
{
    /** @var Registry  */
    private $_registry;

    /** @var Product  */
    private $_Product;

    /** @var session  */
    private $session;

    /** @var session  */
    private $stockRegistry;

    /**
     * StockLeft constructor.
     * @param Context $context
     * @param Registry $registry
     * @param Product $product
     * @param SessionManagerInterface $session
     * @param array $data
     */
    public function __construct(
        Context $context,
        Registry $registry,
        Product $product,
        SessionManagerInterface $session,
        StockRegistryInterface $stockRegistry,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->_registry = $registry;
        $this->_Product = $product;
        $this->session = $session;
        $this->stockRegistry = $stockRegistry;
    }

    /**
     * @return string
     */
    public function getRemainingQty($productId) {
    $stock = $this->stockRegistry->getStockItem($productId);
    return $stock->getQty();
}

    /**
     * @return Magento\Catalog\Model\Product
     */
    protected function getCurrentProduct() {
        return $this->_registry->registry('current_product')->getId();
    }


}

Template file

Custom/Modulestock/view/frontend/templates/stock_left.phtml

<?php 
/**
 * @copyright Devidas
 *
 * @see PROJECT_LICENSE.txt
 *
 *@var Custom\Modulestock\Block\StockLeft $block
 **/
$productId = $this->getProductId();
$RemainingQty = $block->getRemainingQty($productId);

?>
<p>Qty Available: <?php echo $RemainingQty; ?></p>

Override catalog_product_view.xml and add below XML

<referenceContainer name="product.info.main">
            <container name="productdetailstockleft"  htmlTag="div" htmlClass="productdetailstockleft"  after="product.info.price">
                <block class="Custom\Modulestock\Block\StockLeft" name="stockleftproduct" template="Custom_Modulestock::stock_left.phtml" />
            </container>
</referenceContainer>
11
  • Where I should put this? In app/code? Custom\Modulestock\Block\StockLeft.php example: app/code/mymodule/Modulestock/Block/StockLeft.php right?
    – Sylvester
    Commented Feb 21, 2020 at 8:12
  • yes create new module
    – Devidas
    Commented Feb 21, 2020 at 12:59
  • because it's Magento 2 standard.
    – Devidas
    Commented Feb 21, 2020 at 13:00
  • don't directly use code in template file
    – Devidas
    Commented Feb 21, 2020 at 13:01
  • create the module and add above files in your module and check
    – Devidas
    Commented Feb 21, 2020 at 13:02
1

You Dont have variable $productId in your script. Try below code.

<?php
$_helper = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Catalog\Helper\Output');
$_product = $this->getProduct();
$productId = $_product->getId();
$options = $_product->getOptions();
$matrix = $this->getPriceMatrix(2);
/*
* border="0" cellspacing="0" cellpadding="0"
*/
?>
<?php if ($matrix && is_array($matrix)) : ?>
   <h4 class="product name product-item-name">
                                            <?php 
                        $optionText = '';
                        $attr = $_product->getResource()->getAttribute('mgs_brand');
                        if ($attr->usesSource()) {
                           $optionText = $attr->getSource()->getOptionText($_product->getMgsBrand());
                        }
                    ?>
                    <?php if($optionText){ ?>
                        <div class="brand-name"><?php echo $optionText ?></div>
                    <?php } ?>
                        </h4><br />
<table style="width:100%">
    <tbody>
    <?php foreach ($matrix as $r => $variant) : ?>
        <tr class="<?php echo ($r % 2) == 0 ? 'odd' : 'even'; ?>">
            <td style="text-align:left;width:50%">
                <?php $i = 0;
                foreach ($variant['attributes'] as $attribute => $variants) :$i++ ?>
                    <?php if ($i > 1) : ?><br/><?php endif; ?>
                    <span class="label"><?php echo $attribute; ?><span>: </span></span>
                    <span class="data"><?php $idx = 0;
                        foreach ($variants as $name => $tmp) : ?><?php echo $idx++ ? ',' : ''; ?><?php echo $name; ?><?php endforeach; ?></span>
                <?php endforeach; ?>
            </td>
            <td style="text-align:right;width:30%">
                <div class="bl-price-variants"><?php echo $variant['price_formated']; ?></div>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
<?php
echo "Total qty: ";
?>
<?php 
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$StockState = $objectManager- 
>get('\Magento\CatalogInventory\Api\StockStateInterface');
echo $StockState->getStockQty($productId);
?>
<hr />
<?php endif; ?>
2
  • Parse error: syntax error, unexpected '>' in /home/usr/domains/domain.com/public_html/app/code/Snmportal/Publication/data/generator/price_variants2.phtml on line 3
    – Sylvester
    Commented Feb 21, 2020 at 8:11
  • @Sylvester , edited my answer. please check now Commented Feb 22, 2020 at 5:04

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.