如何获得使用递归2 Magento的类别和子类别?我能够显示所有类别,但问题是我需要在一个树状的方式显示它如下面
但是,我得到的是所有这一类的显示。有没有办法实现上述样本?现在我的代码看起来是这样的
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的,我不知道任何文档/教程中,我可以遵循。
非常感谢您对这个帮助。
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);