1

I'm trying to get image for category in magento 2

\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\Layer\Resolver $layerResolver,

public function getCurrentCategory()
{
    return $this->_catalogLayer->getCurrentCategory();
}

public function getCurrentChildCategories()
{
    $categories = $this->_catalogLayer->getCurrentCategory()->getChildrenCategories();
    return $categories;
}

public function getCurrentChildSubCategories($cat)
{
    $subcategories = $cat->getChildrenCategories();
    return $subcategories;
}

and phtml:

<?php $_categories = $block->getCurrentChildCategories(); ?>
<?php
foreach ($_categories as $category):
    echo ("</br>".$category->getName());
    $_subcategories = $block->getCurrentChildSubCategories($category);
    foreach ($_subcategories as $subcategory):
        echo ("</br>_".$subcategory->getName());
    endforeach;
endforeach;
?>

but there are no image href column name in category collection. How can I get image in category collection or how can i get image by entity_id in magento 2 correctly? Any suggestions will be helpful.

2 Answers 2

2

You should add an event in etc/frontend/events.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_category_flat_loadnodes_before">
        <observer name="add_image_to_collection" instance="Namespace\Module\Observer\AddImage" />
    </event>
</config>

and the observer:

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class AddImage implements ObserverInterface
{
    /**
     * @param Observer $observer
     * @return $this
     */
    public function execute(Observer $observer)
    {
        $select = $observer->getSelect();
        return $select->columns('image');
    }
}
1
  • 1
    Which observer? And does that frontend/events.xml go in the themes etc folder?
    – Octoxan
    Commented Feb 28, 2018 at 14:55
0

Your block code should be:

<?php

namespace Module\Name\Block;

class CategoriesCollection extends \Magento\Framework\View\Element\Template
{
     protected $_categoryHelper;
     protected $categoryFlatConfig;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Helper\Category $categoryHelper,
        \Magento\Catalog\Model\Indexer\Category\Flat\State $categoryFlatState
    ) {
        $this->_categoryHelper = $categoryHelper;
        $this->categoryFlatConfig = $categoryFlatState;
        parent::__construct($context);
    }
    /**
     * Return categories helper
     */   
    public function getCategoryHelper()
    {
        return $this->_categoryHelper;
    }

   public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
    {
        return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);
    }

    public function getChildCategories($category)
    {
           if ($this->categoryFlatConfig->isFlatEnabled() && $category->getUseFlatResource()) {
                $subcategories = (array)$category->getChildrenNodes();
            } else {
                $subcategories = $category->getChildren();
            }
            return $subcategories;
    }
}
?>

Your template code should be:

<?php
$categories = $this->getStoreCategories(true,false,true);
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryHelper = $this->getCategoryHelper();
$_outputhelper = $this->helper('Magento\Catalog\Helper\Output');
?>
<div class="block widget block-products-list grid">
    <div class="block-content">
        <div class="products-grid grid">
<?php foreach($categories as $category): ?>
<?php 
if (!$category->getIsActive()) { 
        continue;
     }
$subcats = $this->getChildCategories($category);
$_helper = $this->helper('Magento\Catalog\Helper\Output');
?>
            <ol class="product-items widget-product-grid">
                <?php
                foreach ($subcats as $subcat) {
                    if ($subcat->getIsActive()) {
                        $_category = $objectManager->create('Magento\Catalog\Model\Category')->load($subcat->getId());
                        $subcaturl = $categoryHelper->getCategoryUrl($subcat);

                        $_imgHtml = '';
                        if ($_imgUrl = $_category->getImageUrl()) {

                            $_imgHtml = '<img src="' . $_imgUrl . '" />';
                            $_imgHtml = $_outputhelper->categoryAttribute($_category, $_imgHtml, 'image');

                            /* @escapeNotVerified */
                            echo '<li class="product-item"><div class="product-item-info"><a href="' . $subcaturl . '" class="product-item-photo" title="' . $subcat->getName() . '"><span class="product-image-container"><span class="product-image-wrapper">' . $_imgHtml . '</span></span></a></div></li>';
                        }

                    }
                } ?>
            </ol>
<?php endforeach; ?>
        </div>
    </div>
</div>
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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