I need a way to show products from a category and created a module following the advice of this answer of Marius (https://magento.stackexchange.com/users/146/marius) here: Magento 2: get product collection using category id
I did create a new module though with these files:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'{Company}_GetProductCollection',
__DIR__
);
as registration.php in app/code/{Company}/GetProductCollection
Then
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="{Company}_GetProductCollection" setup_version="1.0.0"></module>
</config>
as module.xml in in app/code/{Company}/GetProductCollection/etc and
<?php
namespace {Company}\GetProductCollection\Block;
class CeloGetProductCollection
{
protected $categoryFactory;
public function __construct(
\Magento\Catalog\Model\CategoryFactory $categoryFactory
){
$this->categoryFactory = $categoryFactory;
}
public function getCategory()
{
$categoryId = $this->getCategoryId();
$category = $this->categoryFactory->create()->load($categoryId);
return $category;
}
public function getProductCollection()
{
return $this->getCagetory()->getProductCollection()->addAttributeToSelect('*');
}
}
as CeloGetProductCollection.php in app/code/{Company}/GetProductCollection/Block
I registered the module successfully with setup:upgrade.
Then bound the file into the page Home Page with:
{{block class="{Company}\GetProductCollection\Block\CeloGetProductCollection" category_id="15" template="Magento_Theme::html/discover_news.phtml"}}
and discover_news.phtml is in my theme directory. Having this content:
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
?>
<?php foreach ($this->getProductCollection() as $product) : ?>
print_r($product,true);
<?php endforeach;?>
What's missing? Because I get the page but instead the oroduct info I get:
Module created gives Error filtering template:
{Company}\GetProductCollection\Block\CeloGetProductCollection does not
implement BlockInterface
Anyone know what's wrong?
Best Answer
The problem is caused by the fact that your block does not extend a Magento native block.
You need to update your block code like this:
On top of that you made a typo
getCagetory
instead ofgetCategory