1

When I try to get product list in a controller for a ajax module like this :

echo $this->layoutFactory->create()
            ->createBlock('\Magento\Catalog\Block\Product\ListProduct')
            ->setCollection($productCollection)
            ->setTemplate('Magento_Catalog::product/list.phtml')
            ->toHtml();

I have this error : Fatal error: Uncaught Error:

Call to a member function setData() on bool in /var/www/magento2/vendor/magento/module-catalog/Block/Product/ListProduct.php:419 Stack trace: 
#0 /var/www/magento2/vendor/magento/module-catalog/Block/Product/ListProduct.php(391): Magento\Catalog\Block\Product\ListProduct->getPriceRender() 
#1 /var/www/magento2/generated/code/Magento/Catalog/Block/Product/ListProduct/Interceptor.php(180): Magento\Catalog\Block\Product\ListProduct->getProductPrice(Object(Magento\Catalog\Model\Product\Interceptor)) 
#2 /var/www/magento2/app/design/frontend/Vital/vital/Magento_Catalog/templates/product/list.phtml(121): Magento\Catalog\Block\Product\ListProduct\Interceptor->getProductPrice(Object(Magento\Catalog\Model\Product\Interceptor)) 
#3 /var/www/magento2/vendor/magento/framework/View/TemplateEngine/Php.php(59): include('/var/www/magent...') 
#4 /var/www/magento2/vendor/magento/module-developer/Model/TemplateEngine/Decorator/DebugHints.php(46): Magento\Framework\View\TemplateEngine\Php->render(Object(Magento\Catal in /var/www/magento2/vendor/magento/module-catalog/Block/Product/ListProduct.php on line 419

Does anyone know where the problem is coming from and how to solve it?

Thanks

1 Answer 1

0

For load product collection, you can take reference from below code:

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();
    $collection->addAttributeToSelect('*');
    $collection->setPageSize(3); // fetching only 3 products
    return $collection;
}
1
  • Thank you for your response but my problem is not on load product list it's on print phtml of product list using ajax.
    – Ben Bogue
    Commented Jun 16, 2020 at 13:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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