How to get stock quantity of each product in list.phtml in Magento 2 ?
Magento2 Stock – How to Get Product Quantity
magento2quantitystock
Related Solutions
You will need to join the table to get qty.
See below code:
$products = Mage::getModel('catalog/product')
->getCollection()
//->addAttributeToSelect('*')
->addAttributeToSelect(array('name', 'thumbnail', 'weight' ,'price','description'))
->joinField(
'qty',
'cataloginventory/stock_item',
'qty',
'product_id=entity_id',
'{{table}}.stock_id=1',
'left'
);
foreach ($products as $product) {
$p['products'][] = array(
'id' => $product->getId(),
'sku' => $product->getSku(),
'name' => $product->getName(),
'description' => $product->getDescription(),
'weight' => $product->getWeight(),
'created at' => $product->getCreatedAt(),
'pirce' => Mage::helper('core')->currency($product->getPrice(), true, false), //." ".$currencyCode,
//get qty
'qty' => $product->getQty(),
);
}
How to get created attribute value here for eg i have created a attribute named size how to fetch that value
UPDATE (Although you should ask in another qst, but I will answer here for you.)
To get custom attribute you will need to add attribute in ->addAttributeToSelect
section.
You might need to load a product model as sometimes I've experienced that not all custom attributes are attached when you pull it out of a collection (intended for performance reasons I guess). Something like:
$_product = Mage::getModel('catalog/product')->load($product->getId());
$size = $_product->getSize();
You have to just create block file keep below code in block file,
app/code/Vendor/Extra/Block/Grouped.php file,
<?php
namespace Vendor\Extra\Block;
use Magento\Catalog\Helper\Data;
class Grouped extends \Magento\Framework\View\Element\Template
{
protected $productRepository;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\CatalogInventory\Model\Stock\StockItemRepository $stockItemRepository,
array $data = []
){
$this->_stockItemRepository = $stockItemRepository;
parent::__construct($context,$data);
}
public function getProductQty($id){
if(is_numeric($id)){
$product = $this->_stockItemRepository->get($id);
return $product->getQty();
}else{
return;
}
}
}
app/design/frontend/{Vendor}/{themename}/Magento_GroupedProduct/templates/product/view/type/grouped.phtml
Inside foreach loop in above file,
<?php
$blocks = $this->getLayout()->createBlock('Vendor\Extra\Block\Grouped');
foreach ($_associatedProducts as $_item):
echo $qtys = $blocks->getProductQty($_item->getId());
endforeach;
?>
Best Answer
Solution:1
Create Helper file Stock.php in your module
After add bellow code in your list.phtml file
Solution:2
Add bellow code in your
list.phtml
fileOR