magentomagento2magento-2.0magento2.2magento2.1

Display Frontend Category URL in Backend Magento


Hi how can I retrieve the value of a category url in the backend? I'm expecting the url value to be equivalent to the url in the frontend and NOT the url in the backend. Is there a way to achieve this in Magento 2?


Solution

  • Ok I found the answer for this. The solution is to use an App/Emulator that is available in Magento. The idea is to start the emulation before you execute the Frontend Catgory URL retrieval that you want and close the emulation when its done.

    Here are the links on how to implement it App Emulation. Didn't know it was this simple to solve the issue. Below is how my code looks like

    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;
        }
    }
    

    So the idea here is to instantiate the emulator and make magento think that you are going to modify or perform like you are in the frontend hence the code \Magento\Framework\App\Area::AREA_FRONTEND when you close the environment emulation it will go back to how it was whether you are in adminhtml or frontend