0

I am creating a new module in magento2 and in controller file, I try to get product collection in controller index.php file so how can I get product collection in Magento 2. so give me suggestion to sort it fast. Thank you.

5

Overview of getting product collection in Magento 2

Step 1: Declare in Vendor_ModuleName Block

Step 2: Display product collection in phtml file

..

Step 1: Declare in Vendor_ModuleName Block

You will use a block class of the module Vendor_ModuleName, then possibly inject the object of \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory in the constructor of the module’s block class.

app/code/Vendor/ModuleName/Block/ProductCollection.php

add code this code

<?php
namespace Vendor\ModuleName\Block;
class ProductCollection 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 getProductCollections()
    {
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->setPageSize(3); // fetching only 3 products
        return $collection;
    }
}
?>

You can request the number of the product collection, that is a limited or unlimited number.

Step 2: Display product collection in phtml file

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

$productCollection = $block->getProductCollections();
foreach ($productCollection as $product) {
    print_r($product->getData());     
    echo "<br>";
}

If that you have any queries about the article or any questions in general, use the comment section below!

  • Thank you @Baharuni Asif – MOHIT Oct 2 '19 at 6:54
0

Please try below code in your controller file:

protected $collectionFactory;

public function __construct(
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory
) {
    $this->collectionFactory = $collectionFactory;
}

public function yourMethod()
{

    $productCollection = $this->collectionFactory->create();

    $productCollection->addAttributeToSelect('*');

    foreach ($productCollection as $product){
         echo 'Name  =  '.$product->getName();
    }  
}

Hope It will help you!

0

Check this link for Product Collection

https://www.mageplaza.com/devdocs/how-get-product-collection-magento-2.html

Hope this will help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.