0

I have this code below that display only 3 of my categories. how can i display sub-category of a parent for example category with an ID of 169;

<?php
namespace Category\Categories\Block\Widget;

class CatewithimgWidget extends \Magento\Framework\View\Element\Template implements \Magento\Widget\Block\BlockInterface
{
    protected $_template = 'widget/categorywidget.phtml';

    /**
     * Default value for products count that will be shown
     */
     protected $_categoryHelper;
     protected $categoryFlatConfig;

     protected $topMenu;
     protected $_categoryFactory;

     protected $mainTitle;
     protected $tagLine;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Catalog\Helper\Category $categoryHelper
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Helper\Category $categoryHelper,
        \Magento\Catalog\Model\Indexer\Category\Flat\State $categoryFlatState,
        \Magento\Catalog\Model\CategoryFactory $categoryFactory,
        \Magento\Theme\Block\Html\Topmenu $topMenu
    ) {
        $this->_categoryHelper = $categoryHelper;
        $this->categoryFlatConfig = $categoryFlatState;
        $this->topMenu = $topMenu;
        $this->_categoryFactory = $categoryFactory;
        parent::__construct($context);
    }
    /**
     * Return categories helper
     */
    public function getCategoryHelper()
    {
        return $this->_categoryHelper;
    }

    public function getCategorymodel($id)
    {
         $_category = $this->_categoryFactory->create();
            $_category->load($id);
            return $_category;
    }
    /**
     * Retrieve current store categories
     *
     * @param bool|string $sorted
     * @param bool $asCollection
     * @param bool $toLoad
     * @return \Magento\Framework\Data\Tree\Node\Collection|\Magento\Catalog\Model\Resource\Category\Collection|array
     */

    /**
     * Retrieve collection of selected categories
    */
   public function getCategoryCollection()
    {
        $rootCat = $this->getData('parentcat');


        $category = $this->_categoryFactory->create();
        $collection = $category
                      ->getCollection()
                      ->addAttributeToSelect('image')
                      ->addIdFilter($rootCat);
        return $collection;
    }
    /**
     * Retrieve tag line for widget
    */
    public function getTagLine()
    {
        $tagLine = $this->getData('tagline');
        return $tagLine;
    }
    /**
     * Retrieve main title for widget
    */
    public function getMainTitle()
    {
        $mainTitle = $this->getData('blocktitle');
        return $mainTitle;
    }
}

and phtml file

<?php
    $categories = $this->getCategoryCollection();
    $categoryHelper = $this->getCategoryHelper();
?>
<div class="widget block block-static-block cwiw" id="catewithimg">
    <div class="block-content">
        <div class="content-heading">
            <h2 class="title"><?php echo $this->getMainTitle(); ?></h2>
            <p class="info"><?php echo $this->getTagLine(); ?></p>
        </div>
        <div class="row">
        <?php
        foreach($categories as $category):
            $cat = $this->getCategorymodel($category->getId());
            $image = $cat->getImageUrl();
        ?>
            <?php if($image != null): ?>
                <div class="col-md-4">
                    <a class="category_name" href="<?php echo $cat->getUrl(); ?>">
                       <img src="<?php echo $image; ?>" class="img-responsive category_image" alt="<?php echo $cat->getName(); ?>" />
                        <h3><span><?php echo $cat->getName(); ?></span></h3>
                    </a>
                </div>
            <?php endif; ?>
        <?php endforeach; ?>
        </div>
    </div>
</div>
0

1 Answer 1

0

Try This

app/code/VendoreName/ModuleName/etc

widget.xml

<?xml version="1.0" ?>
<widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:helloworld:Magento_Widget:etc/widget.xsd">
    <widget class="VendoreName\ModuleName\Block\Widget\CategoryList" id="sub_category_list_block">
        <label>Sub-Category Block</label>
        <description>Show sub-category of selected category</description>
        <parameters>
            <parameter name="blocktitle" sort_order="10" visible="true" xsi:type="text">
                <label>Block Title</label>
            </parameter>
            <parameter name="selected_category" xsi:type="select" required="true" source_model="VendoreName\ModuleName\Model\Config\Source\CategoryOptions"
                       visible="true" sort_order="10" >
                <label translate="true">Select Category</label>
            </parameter>
        </parameters>
    </widget>
</widgets>

app/code/VendoreName/ModuleName/Block/Widget

CategoryList.php

<?php

namespace VendoreName\ModuleName\Block\Widget;

use Magento\Framework\View\Element\Template;
use Magento\Widget\Block\BlockInterface;

class CategoryList extends Template implements BlockInterface
{

    // protected $_template = "widget/category_list.phtml";

    protected $_storeManager;
    protected $categoryRepository;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Catalog\Model\CategoryRepository $categoryRepository,
        array $data = []
    ) {
        $this->_storeManager = $storeManager;
        $this->categoryRepository = $categoryRepository;
        parent::__construct($context, $data);
    }

    protected function _construct()
    {
        parent::_construct();
        $this->setTemplate('widget/category_list.phtml');
    }

    public function getChildCategory()
    {
        $catData = $this->getSelectedCategory();
        if ($catData) {
            if ($catData->getChildrenCategories()->count()) {
                return $catData->getChildrenCategories();
            }
        }
        return false;
    }

    public function getSelectedCategory()
    {
        if ($this->getData('selected_category')) {
            return $this->categoryRepository->get(
                $this->getData('selected_category'),
                $this->_storeManager->getStore()->getId()
            );
        }
        return false;
    }

    public function getCategoryData($id)
    {
        return $this->categoryRepository->get(
            $id,
            $this->_storeManager->getStore()->getId()
        );
    }

    public function getCategoryTitle()
    {
        return $this->getData('blocktitle');
    }

}

app/code/VendoreName/ModuleName/Model/Config/Source

CategoryOptions.php

<?php

namespace VendoreName\ModuleName\Model\Config\Source;

use Magento\Framework\Data\OptionSourceInterface;

class CategoryOptions implements OptionSourceInterface
{
    protected $categoryCollectionFactory;

    public function __construct(
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory
    ) {
        $this->categoryCollectionFactory = $categoryCollectionFactory;
    }

    public function toOptionArray()
    {
        return $this->getCategoryTree();
    }

    protected function getCategoryTree()
    {
        $categoryFactory = $this->categoryCollectionFactory->create();
        $categoryFactory->addAttributeToSelect('*');
        $catOptions = [];
        foreach ($categoryFactory as $category) {
            $catOptions[] = [
                'value' => $category->getId(),
                'label' => $category->getName(),
            ];
        }
        return $catOptions;
    }
}

app/code/VendoreName/ModuleName/view/frontend/templates/widget

category_list.phtml

<?php
$currentCategoryData = $block->getSelectedCategory();
$childCatData = $block->getChildCategory();
?>
<div class="widget block block-static-block cwiw" id="catewithimg">
    <div class="block-content">
        <div class="content-heading">
            <h2 class="title"><?= $block->escapeHtml(__($block->getCategoryTitle())) ?></h2>
        </div>
        <div class="row">
            <?php if($childCatData): ?>
                <?php foreach($childCatData as $category): ?>
                    <div class="col-md-4">
                        <a class="category_name" href="<?= $block->escapeUrl($category->getUrl()) ?>">
                            <h3>
                                <span><?= $block->escapeHtml(__($category->getName())) ?></span>
                            </h3>
                        </a>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

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.