Skip to content

Magento 2 render custom template same as Magento_CatalogWidget::product/widget/content/grid.phtml by from ajax controller

I’m trying to render products the same as Magento_CatalogWidget::product/widget/content/grid.phtml displaying.

I have created a custom ajax controller.

        $productCollection->addAttributeToSelect('*');
        $productCollection->setPageSize(10);
        $productCollection->load();

        $block = $layout->createBlock('VendorModuleBlockProductProductsList')->setTemplate('Vendor_Module::product/widget/content/grid.phtml')
            ->setProductCollection($productCollection);

        $html = $block->toHtml();

        $result = $this->resultFactory->create(MagentoFrameworkControllerResultFactory::TYPE_RAW);
        $result->setContents($html);
        return $result;

In Ajax response, I get the below error message:

1 exception(s):
Exception #0 (Exception): Warning: foreach() argument must be of type array|object, null given in /var/www/html/development/vendor/magento/module-catalog-widget/Block/Product/ProductsList.php on line 406

#1 MagentoCatalogWidgetBlockProductProductsList->getConditions() called at [vendor/magento/module-catalog-widget/Block/Product/ProductsList.php:350]