Zend certified PHP/Magento developer

M2: How to get total stock qty

I will try get total stock product qty.

I use this below code:

    < ?php
echo "Total qty: ";
?>
< ?php 
    $objectManager = MagentoFrameworkAppObjectManager::getInstance();
    $StockState = $objectManager->get('MagentoCatalogInventoryApiStockStateInterface');
    echo $StockState->getStockQty($productId);
?>

But script display 0 qty for all products.

Here is full file code:

< ?php
$_helper = MagentoFrameworkAppObjectManager::getInstance()->get('MagentoCatalogHelperOutput');
$_product = $this->getProduct();
$options = $_product->getOptions();
$matrix = $this->getPriceMatrix(2);
/*
 * border="0" cellspacing="0" cellpadding="0"
 */
?>
< ?php if ($matrix && is_array($matrix)) : ?>
       

< ?php $optionText = ''; $attr = $_product->getResource()->getAttribute('mgs_brand'); if ($attr->usesSource()) { $optionText = $attr->getSource()->getOptionText($_product->getMgsBrand()); } ?> < ?php if($optionText){ ?>
< ?php echo $optionText ?>
< ?php } ?>


< ?php foreach ($matrix as $r => $variant) : ?> < ?php endforeach; ?>
< ?php $i = 0; foreach ($variant['attributes'] as $attribute => $variants) :$i++ ?> < ?php if ($i > 1) : ?>
< ?php endif; ?> < ?php echo $attribute; ?>: < ?php $idx = 0; foreach ($variants as $name => $tmp) : ?>< ?php echo $idx++ ? ',' : ''; ?>< ?php echo $name; ?>< ?php endforeach; ?> < ?php endforeach; ?>
< ?php echo $variant['price_formated']; ?>
< ?php echo "Total qty: "; ?> < ?php $objectManager = MagentoFrameworkAppObjectManager::getInstance(); $StockState = $objectManager->get('MagentoCatalogInventoryApiStockStateInterface'); echo $StockState->getStockQty($productId); ?>
< ?php endif; ?>