2016-07-28 66 views

回答

5

尝试以下用于获取类别对象在Magento2代码:

$categoryId = 3; 
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$category = $_objectManager->create('Magento\Catalog\Model\Category') 
->load($categoryId); 
echo $category->getName(); 
9

你不应该使用ObjectManager

您可以在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; 
    } 
} 
相关问题