2

I need to create new module, which allows to display subcategories for a specified category inside block.

I call the block like this:

<block 
  class="Vendor/Module/Block/CategoryList.php" 
  category_id="7" 
  template=Vendor_Module::CategoryList 
/>

Found a lot of solutions here, but couldn't make anyone work for me, I am using magento 2.2.

EDIT: I don't know how correct this is, but I managed to get the result I wanted doing this:

categories.phtml

<div class="menu_categories menu_block">
<?php
$categoryId = $this->getCategoryId();
$categories = $block->getStoreCategories();
$c = 0;

foreach($categories as $category) :
    $c++;

    if($c > 1) {
        break;
    } ?>
    <div class="col-sm-2">
        <ul>
            <?php
            $category = $block->getCategory($categoryId);
            echo '<h3><a href="'.$category->getUrl().'" title="Parent Category">'.$category->getName().'</a></h3>';
            if($category->hasChildren()) {
                $subCategories = $category->getChildrenCategories();

                foreach($subCategories as $subCategory) {
                    $subCategoryObj = $block->getCategoryById($subCategory->getId());
                    echo '<li><a href="'.$subCategoryObj->getUrl().'" title="Subcategory">'.$subCategory->getName().'</a></li>';
                }
            } ?>
        </ul>
    </div>
<?php endforeach;?>

and then I call the template in the block like this:

default.xml

<block class="Vendor\CategoryList\Block\Categories" name="category.list" template="Vendor_CategoryList::categories.phtml">
    <action method="setCategoryId">
        <argument name="category_id" xsi:type="string">42</argument>
    </action>
</block>
  • Ẁhat are you already achieve? – Nolwennig Nov 15 '17 at 14:56
  • What's Block/CategoryList.php code? – Nolwennig Nov 15 '17 at 14:57
  • What's CategoryList.phtml content? – Nolwennig Nov 15 '17 at 14:59
  • My module has this function github.com/magepow/magento2-categories follow this to solve your problem. – MichaelHa Dec 11 '19 at 4:45
2

I have built something similar but my category list shows all store categories and the sub categories underneath for a menu. You could adjust it by passing an argument though.

Block/Categories.php

<?php
namespace Me\My_Store\Block;

class Categories extends \Magento\Framework\View\Element\Template
{
    protected $_categoryFactory;
    protected $_category;
    protected $_categoryHelper;
    protected $_categoryRepository;

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

  /**
     * Get category object
     * Using $_categoryFactory
     *
     * @return \Magento\Catalog\Model\Category
     */
    public function getCategory($categoryId) 
    {
        $this->_category = $this->_categoryFactory->create();
        $this->_category->load($categoryId);
        return $this->_category;
    }

  /**
     * Get category object
     * Using $_categoryRepository
     *
     * @return \Magento\Catalog\Model\Category
     */
    public function getCategoryById($categoryId) 
    {
        return $this->_categoryRepository->get($categoryId);
    }

  /**
     * Retrieve current store categories
     *
     * @param bool|string $sorted
     * @param bool $asCollection
     * @param bool $toLoad
     * @return \Magento\Framework\Data\Tree\Node\Collection or
     * \Magento\Catalog\Model\ResourceModel\Category\Collection or array
     */
    public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
    {
        return $this->_categoryHelper->getStoreCategories();
    }

  /**
     * Get parent category object
     *
     * @return \Magento\Catalog\Model\Category
     */
    public function getParentCategory($categoryId = false)
    {
        if ($this->_category) {
            return $this->_category->getParentCategory();
        } else {
            return $this->getCategory($categoryId)->getParentCategory();
        }
    }

  /**
     * Get parent category identifier
     *
     * @return int
     */
    public function getParentId($categoryId = false)
    {
        if ($this->_category) {
            return $this->_category->getParentId();
        } else {
            return $this->getCategory($categoryId)->getParentId();
        }
    }

  /**
     * Get all parent categories ids
     *
     * @return array
     */
    public function getParentIds($categoryId = false)
    {
        if ($this->_category) {
            return $this->_category->getParentIds();
        } else {
            return $this->getCategory($categoryId)->getParentIds();
        }
    }

  /**
     * Get all children categories IDs
     *
     * @param boolean $asArray return result as array instead of comma-separated list of IDs
     * @return array|string
     */
    public function getAllChildren($asArray = false, $categoryId = false)
    {
        if ($this->_category) {
            return $this->_category->getAllChildren($asArray);
        } else {
            return $this->getCategory($categoryId)->getAllChildren($asArray);
        }
    }

  /**
     * Retrieve children ids comma separated
     *
     * @return string
     */
    public function getChildren($categoryId = false)
    {
        if ($this->_category) {
            return $this->_category->getChildren();
        } else {
            return $this->getCategory($categoryId)->getChildren();
        }
    }
}
?>

.

categories.phtml

<div class="row menu-links">
<?php
$categories = $block->getStoreCategories();
$c = 0;

foreach($categories as $category) : 
  $c++;

  if($c > 6) {
      break;
  } ?>
  <div class="col-sm-2">
      <ul>
      <?php
      $categoryObj = $block->getCategoryById($category->getId());
      echo '<li class="parent"><a href="'.$categoryObj->getUrl().'">'.$category->getName().'</a></li>';

      if($category->hasChildren()) {
          $subCategories = $categoryObj->getChildrenCategories();

          foreach($subCategories as $subCategory) {
              $subCategoryObj = $block->getCategoryById($subCategory->getId());
              echo '<li><a href="'.$subCategoryObj->getUrl().'">'.$subCategory->getName().'</a></li>';
          }
      } ?>
      </ul>
  </div>
<?php endforeach;?>
</div>
| improve this answer | |
  • thank you very much, it works, just need to understand how to display only one category subcategories – Rihards Repels Nov 22 '17 at 11:06
  • This only get 1 sub product like, Rihards Repels said, but other than that the code works great! – KyleBunga Dec 18 '19 at 22:01

Your Answer

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

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