【发布时间】:2016-12-03 00:47:21
【问题描述】:
你好,我是 magento2 的新手
我想从指定的类别 id 中获取类别名称 有人可以帮忙吗?
提前致谢
【问题讨论】:
标签: magento2
你好,我是 magento2 的新手
我想从指定的类别 id 中获取类别名称 有人可以帮忙吗?
提前致谢
【问题讨论】:
标签: magento2
你不应该使用ObjectManager。
你可以把这个放到Block里面,然后在phtml里面调用函数getCategoryName():
namespace Company\Module\Block;
class CustomBlock extends \Magento\Framework\View\Element\Template
{
protected $_categoryFactory;
public function __construct(
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
\Magento\Framework\View\Element\Template\Context $context,
) {
$this->_categoryFactory = $categoryFactory;
parent::__construct($context);
}
public function getCategoryName()
{
$categoryId = '43';
$category = $this->_categoryFactory->create()->load($categoryId);
$categoryName = $category->getName();
return $categoryName;
}
}
【讨论】:
尝试以下代码在 Magento2 中获取类别对象:
$categoryId = 3;
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $_objectManager->create('Magento\Catalog\Model\Category')
->load($categoryId);
echo $category->getName();
【讨论】: