I am using Magento 2.2.1. I cannot get the product collection when i use dependency injection. I wonder if I have left out something that needs to be done. for example, do I need to feed the product object into the injection?

This is the code:

namespace Test\HelloWorld\Block;
class HelloWorld 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();
        return $collection;


Then on my phtml page I do this:

$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
    echo "<br>";

The page comes back with a black, no error messages, just a blank page.

However, if i use the object manager to get the product collection it works: THE CODE BELOW WORKS

public function getProduct()
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

        $productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');

        $collection = $productCollection->create()

        return $collection;

  • Try to remove page size from DI than check., OR you can use $collection->addAttributeToSort('entity_id','desc'); Make sure you have visible products, Check Answer by Monarch1.
    – anonymous
    Apr 12 '18 at 10:49
  • why you have using different function on different sceneio getProduct and getProductCollection.
    – Amit Bera
    Apr 12 '18 at 11:03
protected $collectionFactory;

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

public function yourMethod() {
    $productCollection = $this->collectionFactory->create();
    foreach ($collection as $product){   
    enter code here

  • no no. you misunderstand. i dont want to use the object manager. i want to use dependency injection. my object manager works already. its the DI that does work Apr 12 '18 at 10:52
  • Paul, Please use updated function,
    – Shinesh
    Apr 12 '18 at 10:59
  • If you post code as an answer, please at least explain briefly what this code is doing and where it belongs. Answers with code but no explanation are rarely useful.
    – 7ochem
    Apr 12 '18 at 13:08

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.