获取类别和子类别的树形显示

问题描述 投票:1回答:1

如何获得使用递归2 Magento的类别和子类别?我能够显示所有类别,但问题是我需要在一个树状的方式显示它如下面

  • 默认分类 家 关于我们 制品 P-一个 SC-四 P-2 SC-一 SC-TWO 网站地图 SC-一

但是,我得到的是所有这一类的显示。有没有办法实现上述样本?现在我的代码看起来是这样的

class Index extends \Magento\Framework\View\Element\Template 
{

protected $_categoryCollectionFactory;
protected $_categoryHelper;
protected $_categoryRepository;
protected $_storeManager;

public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
    array $data = []
)
{
    $this->_categoryCollectionFactory = $categoryCollectionFactory;
    $this->_categoryHelper = $categoryHelper;
    $this->_categoryCategoryRepository = $categoryRepository; 
    $this->_storeManager = $storeManager;
    $this->layerResolver = $layerResolver;
    parent::__construct($context, $data);
}

/**
 * Get category collection
 *
 * @param bool $isActive
 * @param bool|int $level
 * @param bool|string $sortBy
 * @param bool|int $pageSize
 * @return \Magento\Catalog\Model\ResourceModel\Category\Collection or array
 */
public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false)
{
    $collection = $this->_categoryCollectionFactory->create();
    $collection->addAttributeToSelect('*');

    // Select only active categories
    if ($isActive) {
        $collection->addIsActiveFilter();
    }

    // select categories of certain level
    if ($level) {
        $collection->addLevelFilter($level);
    }

    // sort categories by some value
    if ($sortBy) {
        $collection->addOrderField($sortBy);
    }

    // select certain number of categories
    if ($pageSize) {
        $collection->setPageSize($pageSize);
    }

    return $collection;
}

在我的PHTML文件我有这个

$categories = $this->getCategoryCollection();
foreach ($categories as $category) {
    echo $category->getName() . '<br />';
}

我不知道该怎么做这件事,这将是巨大的,如果我还可以得到任何Magento的2文档它教你如何让喜欢的产品和其他的东西在网站的不同部分的参考。现在我有零知识与Magento的,我不知道任何文档/教程中,我可以遵循。

非常感谢您对这个帮助。

magento2
1个回答
1
投票

Magento\Theme\Block\Html\Topmenu座已经给你所有类别和子类别递归查询PHTML文件/vendor/magento/module-theme/view/frontend/templates/html/topmenu.phtml你可以用菜单下面的代码

<?php $columnsLimit = $block->getColumnsLimit() ?: 0; ?>
<?php echo $_menu = $block->getHtml('level-top', 'submenu', $columnsLimit) ?>

上面的代码将让你在HTML树结构的类别。你也可以重写块Magento\Theme\Block\Html\Topmenu在你需要的格式获得输出。

要么

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryFactory = $objectManager->create('Magento\Catalog\Helper\Category');
$all = $categoryFactory->getStoreCategories(false,true,true);
© www.soinside.com 2019 - 2024. All rights reserved.