1

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();
?>
0

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();
  • little bit lengthy criteria, but I will try this – Magedev2301 May 6 at 9:53
  • Thanks. worked for me – Magedev2301 May 6 at 10:12
  • Great, welcome. please vote on answer too if it is helpful to you – Shoaib Munir May 6 at 10:20

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.