The product grid of a category page (frontend) is rendered via layout in catalog_category_view.xml.
Lets say I have a custom product collection (which I got via
ProductRepositoryInterface::getList($searchCriteria) method
in a custom block class and want to render this collection. The rendered result should be displayed as a product grid on frontend (just like any category page).
How can this be done ?
By looking into catalog_category_view.xml
there are two significant lines, which are responsible for rendering a product collection:
<block class="Magento\Catalog\Block\Category\View" name="category.products" template="Magento_Catalog::category/products.phtml">
<block class="Magento\Catalog\Block\Product\ListProduct" name="category.products.list" as="product_list" template="Magento_Catalog::product/list.phtml">
How can I provide my custom product collection to these template files, so they render my collection ?
Correct me, if I am wrong on this.
This is how my block code looks like:
<?php
namespace Mod\Mod1\Block;
use Magento\Framework\View\Element\Template;
class Main extends Template
{
protected $_filterBuilder;
protected $_filterGroupArray;
protected $_filterGroupBuilder;
protected $_searchCriteriaBuilder;
protected $_productRepository;
protected $_productFactory;
protected $_list;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
\Magento\Framework\Api\Search\FilterGroupBuilder $filterGroupBuilder,
\Magento\Framework\Api\FilterBuilder $filterBuilder,
\Magento\Catalog\Model\ProductFactory $productFactory,
array $data = [])
{
$this->_productRepository = $productRepository;
$this->_searchCriteriaBuilder = $searchCriteriaBuilder;
$this->_filterGroupBuilder = $filterGroupBuilder;
$this->_filterBuilder = $filterBuilder;
parent::__construct($context, $data);
}
public function getLoadedProductCollection(){
$searchCrit = $this->buildSearchCriteria('','','','','','5-',1);
$list = $this->_productRepository->getList($searchCrit);
return $list;
}
public function buildSearchCriteria(...){
....
return $searchCriteria;
}
}
Best Answer
You can try this:
Update your catalog_category_view.xml
And call yourFile.phtml in product/list.phtml:
Now, you can use your function in yourfile.phtml like this:
Example:
Hope this can help you.