1

I'd like to show a list of products on my homepage. I've added a block in my layout.xml file and assigned a template to it. In this template I'm using a Helper Class.

Here's the code of my Helper Class:

namespace Vendor\Module\Helper;

class CategoryHelper extends \Magento\Framework\App\Helper\AbstractHelper {

    protected $_categoryFactory;

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

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

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

}

Here's the code of my .phtml file:

$categoryProducts = $block->getCategoryProducts( 8 );

foreach ($categoryProducts as $product) {
    echo $product->getName() . ' - ' . $product->getProductUrl() . '<br />';
}

No matter what ID I use, magento 2 shows up the following error message:

Exception #0 (Exception): Warning: Invalid argument supplied for foreach() in [...]/app/design/frontend/Vendor/Module/Magento_Theme/templates/page/home/single_category.phtml on line 5


UPDATE:

I have changed the .phtml file to:

$categoryProducts = $this->helper('Vendor\Module\Helper\CategoryHelper')->$block->getCategoryProducts( "8" ); 

Now I get the following exception:

Exception #0 (Exception): Recoverable Error: Argument 1 passed to Vendor\Module\Helper\CategoryHelper::__construct() must be an instance of Magento\Framework\App\Helper\Context, instance of Magento\Backend\Block\Template\Context given, called in [...]/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php on line 93 and defined in [...]/app/code/Vendor/Module/Helper/CategoryHelper.php on line 10

I've also updated the Helper Class and changed the vartype from $context to Magento\Framework\App\Helper\Context...

  • First check is it going in your helper function or not ? by echo in that function , or else try something like this - $helper = $this->helper('{Vendor}\{Module}\Helper\Data'); and $values = $helper->getCategoryProducts(8); – Manthan Dave Aug 8 '17 at 8:48
  • Yes it does, tried it before by printing "foo" – DaFunkyAlex Aug 8 '17 at 9:36
  • The error is clear you have issue with the data , lets do one thing print array of $categoryProducts in your phtml file and post the result what you are getting . – Manthan Dave Aug 8 '17 at 9:51

Your Answer

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

Browse other questions tagged or ask your own question.