3

I have custom collection in $collection I want to pass it to list.phtml so that I don't have to create listing UI again. I am trying to do this but it is not working

<?php
echo $this->getLayout()
                ->createBlock("Magento\Catalog\Block\Product\ListProduct")
                ->setProductCollection($collection)
                ->setTemplate("Magento_Catalog::product/list.phtml")
                ->toHtml();
?>
Shoaib Munir
  • 9,404
  • 10
  • 49
  • 106
Magedev2301
  • 230
  • 2
  • 22
  • 1
    Checkout this: https://magento.stackexchange.com/questions/148680/use-product-list-template-with-my-own-product-collection – Saphal Jha May 06 '19 at 10:09

2 Answers2

1

Better solution to write your colection and add in above template such as


   $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->setPageSize(3); // fetching only 3 products
        $block = $resultPage->getLayout()
            ->createBlock('Magento\Catalog\Block\Product\ListProduct')
            ->setCollection($collection)
            ->setTemplate("Magento_Catalog::product/list.phtml")
              ->toHtml();

-1

This was possible in Magento 1.9 to pass product collection to list.phtml, but you cannot do this in Magento 2.

The proper way to do this is to create your own Block file

app/code/Vendor/Module/Block/ProductList.php

Code will be:

<?php
namespace Vendor\Module\Block;

class ProductList extends \Magento\Catalog\Block\Product\ListProduct
{

    protected function _getProductCollection()
    {
        if ($this->_productCollection === null) {

            //Generate your collection here

            $this->_productCollection = $collection;
        }

        return $this->_productCollection;
    }
}

Now call list.phtml using your custom Block

echo $this->getLayout()
    ->createBlock("Vendor\Module\Block\ProductList")
    ->setTemplate("Magento_Catalog::product/list.phtml")
    ->toHtml();
Shoaib Munir
  • 9,404
  • 10
  • 49
  • 106