Get product collection using a factory method in a block file in magento:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
namespace Vendorname\Modulename\Block; class Product extends \Magento\Framework\View\Element\Template { protected $productFactory; public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory, array $data = [] ) { $this->productFactory = $productFactory; parent::__construct($context, $data); } public function getProductCollection() { $collection = $this->productFactory->create(); return $collection; } } |
How to get product collection in .phtml file. getProductCollection method form our block file.
1 2 3 4 5 6 7 |
$productCollection = $block->getProductCollection(); foreach ($productCollection as $product) { echo “<pre>”; print_r($product->getData()); echo “</pre>”; } |
You can get objectManager throw get product collection but it’s not proper way.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $productCollection = $objectManager->create(‘Magento\Catalog\Model\ResourceModel\Product\CollectionFactory’); $collection = $productCollection->create() ->addAttributeToSelect(‘*’) ->load(); foreach ($collection as $product){ echo “<pre>”; print_r($product->getData()); echo “</pre>”; } |