0

I have a template from a customer's Magento 1 theme that I need to move to M2. The theme isn't the same but the template does what I need it to on M1 and I need this in Magento 2.

    <ul class="row list">
        <?php 
        $parentCategoryId = 20;
        $cat = Mage::getModel('catalog/category')->load($parentCategoryId);
        $subcats = $cat->getChildren(); 
        foreach(explode(',',$subcats) as $subCatid){
            $_category = Mage::getModel('catalog/category')->load($subCatid);
            if($_category->getIsActive()) {
                $image = Mage::getBaseUrl('media') . 'catalog/category/' . $_category->getThumbnail();
                $imageCheck = $_category->getThumbnail();
                $name = $_category->getName();
                echo '<li class="col-md-3 col-sm-6" style="list-style:none;">';
                    echo '<a href="' . $_category->getUrl() . '">';
                        if ($imageCheck == ''){ $image = $this->getSkinUrl('images/noPic.jpg'); }
                        echo '<img src="' . $image  .'" style="width:100%;">';
                        echo '<p class="text-center artist-name">' . $name . '</p>';
                    echo '</a>';
                echo '</li>';
            }
        }
        ?>
    </ul>

This is PHTML from M1, which I did not write. In effect, it loads all subcategories of a parent category then displays them in a grid with the category title and thumbnail. If I have to create a small extension then call what I need in a PHTML, that's fine but I'm still a little new to M2 so I'm not sure where to start.

I did find this answer and I'm using the top bit with the object manager: https://magento.stackexchange.com/a/201951/69191

I know that's probably not the best practice but is it passable in a template file, or is there a better way?

1
  • most of what you need is in the answer you referenced, just create a module with a helper or block class to return the category object then update your phtml code to parse the data.
    – paj
    Commented Jan 28, 2020 at 20:03

1 Answer 1

2

Create a new module Your_Module - a simple way to do this is with n98-magerun2

n98-magerun2.phar dev:module:create

Add a new block class in Your/Module/Block, eg - Category.php

<?php
namespace Your\Module\Block;

use Magento\Framework\View\Element\Template\Context;
use Magento\Framework\Registry;
use Magento\Catalog\Model\CategoryFactory;

class Category extends \Magento\Framework\View\Element\Template
{
        protected $_registry;
        protected $_categoryFactory;

    public function __construct(
        Context $context,
        Registry $registry,
        CategoryFactory $categoryFactory,
        array $data = []
    )
    {
        $this->_registry = $registry;
        $this->_categoryFactory = $categoryFactory;
        parent::__construct($context, $data);
    }

    public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }


    /**
    * Get children categories
    * @param $categoryId Parent category id
    * @return Magento\Catalog\Model\ResourceModel\Category\Collection
    */
    public function getChildCategories($categoryId)
    {

        $_category = $this->_categoryFactory->create();

        $category = $_category->load($categoryId);

        //Get category collection
        $collection = $category->getCollection()
                ->addIsActiveFilter()
                ->addAttributeToSelect('*')
                ->addOrderField('name')
                ->addIdFilter($category->getChildren());


        return $collection;
    }

}
?>

In your template use the block to obtain the category data

categorylist.phtml

<?php
// CATEGORY LIST template
//
$blockCategory= $block->getLayout()->createBlock('Your\Module\Block\Category');

$parentCategoryId = 38;
$subcats=$blockCategory->getChildCategories($parentCategoryId);

?>
<div>
    <ul class="row list">
        <?php

        foreach($subcats as $category){

            if($category->getIsActive()) {
                echo '<li class="col-md-3 col-sm-6" style="list-style:none;">';
                    echo '<a href="' . $category->getUrl() . '">';
                        $imageUrl=$category->getImageUrl();
                        if ($imageUrl == ''){ $image = '/BLAH/noPic.jpg'; }
                        echo '<img src="' . $imageUrl  .'" style="width:10%;">';
                        echo '<p class="text-center artist-name">' . $category->getName() . '</p>';
                    echo '</a>';
                echo '</li>';
            }
        }
        ?>
    </ul>
</div>

You may need to play with the "No Pic" logic and image size (not sure if there are category thumbnails in Mage 2?) and add helpers to return Mage 2 media base urls if you need them.

2
  • Thanks a ton! I can run with this.
    – Marisa
    Commented Jan 29, 2020 at 16:28
  • 1
    Thats not very clean, you should not use buisness logic in the template... outsource the foreach to a function in the block class and call it in the template... e.g. $block->myfunction()
    – Black
    Commented Jan 29, 2020 at 16:43

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.