嗨,我如何在后端检索类别URL的值?我期望url值等于前端中的url,而不是后端中的url。在Magento 2中有没有办法实现这一目标?
答案 0 :(得分:0)
好的,我找到了答案。解决方案是使用Magento中提供的App / Emulator。这个想法是在执行所需的前端类别URL检索之前开始仿真,并在完成后关闭仿真。
以下是有关如何实现它的链接App Emulation。不知道解决这个问题很简单。下面是我的代码的样子
class MenuCategory extends \Magento\Framework\Model\AbstractModel implements \Magento\Framework\DataObject\IdentityInterface
{
public function getStoreCategories($storeManager, $emulator)
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$emulator->startEnvironmentEmulation(null, \Magento\Framework\App\Area::AREA_FRONTEND, true);
$categoryFactory = $objectManager->create('Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$categories = $categoryFactory->create()
->addAttributeToSelect('*')
->setStore($storeManager->getStore())
->addAttributeToFilter('level', array('eq' => 2))
->addIsActiveFilter()
->addAttributeToSort('position', 'asc');
foreach ($categories as $category) {
echo $category->getUrl() . " - " . $category->getUrl() . "\n";
}
$emulator->stopEnvironmentEmulation();
return $content;
}
}
因此,这里的想法是实例化模拟器,并使magento认为您将像在前端一样进行修改或执行,因此代码 \ Magento \ Framework \ App \ Area :: AREA_FRONTEND 当您关闭环境仿真时,它将回到原来的状态,无论您使用的是adminhtml还是前端
答案 1 :(得分:-1)
要获取类别网址,您需要像这样使用Magento\Catalog\Model\CategoryRepository
函数getUrl()
:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$emulator->startEnvironmentEmulation(null, \Magento\Framework\App\Area::AREA_FRONTEND, true);
$categoryFactory = $objectManager->create('Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$categories = $categoryFactory->create()
->addAttributeToSelect('*')
->setStore($storeManager->getStore())
->addAttributeToFilter('level', array('eq' => 2))
->addIsActiveFilter()
->addAttributeToSort('position', 'asc');
foreach ($categories as $category) {
$categoryObject = $objectManager->create('Magento\Catalog\Model\CategoryRepository')->get($category->getId());
echo $categoryObject->getUrl()."\n";
}