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>