Magento 2 Get product collection in a custom template block

  • I have defined a featured product template in a cms static page as below:

    {{block class="Magento\Catalog\Block\Product\ListProduct" template="Magento_Catalog::product/featured.phtml"}}

    Now I want to load original product collection(without any filters applied, which I am gonna apply later) inside my template "featured.phtml", but I can't find a way to do it directly without creating a module for such a tiny task.

    Somebody let me know, how to do something like below in Magento2, in this case: Mage::getModel('catalog/product')->getCollection()

    Have you tried `\Magento\Catalog\Block\Product\ListProduct::getLoadedProductCollection`? It is accessible in your template just as `$this->getLoadedProductCollection()`.

    Yes tried that already, but it is already a filtered collection with very less products, I need raw colleciton without any filters like `$this->getCollection()`

  • It is better to create custom block for your needs. It is not clear why you can create custom template, but not block. Also have you considered using \Magento\Catalog\Api\ProductRepositoryInterface::getList which is part of Magento public API? Collection should not be manipulated directly.

    Implementation below is a hack (object manager should never be used directly), but the only solution without creation of a new block:

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection */
    $productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
    /** Apply filters here */

    Thanks for reply, can you tell me how to filter this collection by `category_id`, I tried filtering using function `addFieldToFilter` but it gives error, I guess `addField....` function only works for table's own fields not with joining tables.

    `$productCollection->addCategoriesFilter(['in' => [1, 2, 3]])` should work.

    Thanks, your solution is working perfectly for now. Accepting it.

    @AlexPaliarush How do i use filter by attribute and select attribute like name, id, v.v.. via ProductRepository example:$this->_productRepository->getList($this->_searchCriteria)->addAttributeToFilter('is_featured', 1) results undefined method trigger

    @mrtuvn `$this->_searchCriteria` should contain necessary filters. `addAttributeToFilter` is defined for collections and is not available for repositories. Take a look at these answers

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM