Michael
0
Q:

magento2 get product collection

<?php
namespace Foungento\Theme\Block;
class Theme extends \Magento\Framework\View\Element\Template
{    
    protected $_productCollectionFactory;
        
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,        
        array $data = []
    )
    {    
        $this->_productCollectionFactory = $productCollectionFactory;    
        parent::__construct($context, $data);
    }
    
    public function getProductCollection()
    {
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->setPageSize(10); // fetching only 10 products
        return $collection;
    }
}
?>

/*Display product collection in phtml file
Print out the product collection in phtml file with the below code:*/

list.phtml
$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
    print_r($product->getData());     
    echo "<br>";
}
0
$om = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $om->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
$collection = $productCollection->addAttributeToSelect('*')->load();
0

New to Communities?

Join the community