5

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?

  • I now know how to access most items like: echo $product->getName() . ' # ' . $product->getProductUrl() . ' # ' . $product->getPrice(). ' # ' . $product->getDescription() . ' # ' . $product->getFormatedPrice() . ' # ' . $product->getData('small_image') . '<br />'; – user789660 Jun 30 '16 at 8:43
4

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:

<?php

namespace {Company}\GetProductCollection\Block;

class CeloGetProductCollection extends \Magento\Framework\View\Element\Template
{

  protected $categoryFactory;

  public function __construct(
      \Magento\Framework\View\Element\Template\Context $context,
      \Magento\Catalog\Model\CategoryFactory $categoryFactory,
      array $data = []
  ){
      $this->categoryFactory = $categoryFactory;
      parent::__construct($context, $data);
  }

  public function getCategory()
  {
    $categoryId = $this->getCategoryId();
    $category = $this->categoryFactory->create()->load($categoryId);
    return $category;
  }

  public function getProductCollection()
  {
    return $this->getCategory()->getProductCollection()->addAttributeToSelect('*');
  }

}

On top of that you made a typo getCagetory instead of getCategory

| improve this answer | |
  • Thanks alot for your fast answer. I saw classes in magento before that did not extend another class so I thought it will be ok. But it makes sense that this class gets extended. I will see if it get's solved and let you know. :) – user789660 Jun 29 '16 at 11:09
  • When adding the changes I got the php-error "Fatal error: Call to a member function getProductCollection() on null in /var/www/clients/client170/web1213/web/app/code/{Company}/GetProductCollection/Block/CeloGetProductCollection.php on line 29" I tried what happens when I put in return $this->getCategory(); in function getProductCollection() and it seems the function GetCategory() can successfully receive the cat ID but the $category var is empty then. echo gettype($this->getProductCollection()); in .phtml shows it's an object. Don't know how to handle this yet. – user789660 Jun 29 '16 at 11:29
  • @Magento2Noob because your wrote getCagetory instead of getCategory – Raphael at Digital Pianism Jun 29 '16 at 11:29
  • Good find. :D I wonder why netbeans didn't label this already as a typo. Though now, after changing my template to: <?php foreach ($this->getProductCollection() as $product) : print_r($product,true); endforeach;?> I get a blank home page and no related error in system.log. print_r((array)$product,true); does not help and echo gettype($product); make the page appear again and it shows objectobject, because 2 products are in this category. So it seems to work generally, only it does give back an object and I do not know how to handle it.... – user789660 Jun 29 '16 at 12:03
  • @Magento2Noob using print_r to display massive object like products is not recommended as it often ends up in memory exhaustion. I suggest you use xDebug to debug that instead. – Raphael at Digital Pianism Jun 29 '16 at 12:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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