Magento – Magento 2 get image for Subcategory Collection

categoryimagemagento2

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.

Best Answer

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');
    }
}
Related Topic