Question

Please could someone advise why I am getting this error when calling my code below:

Uncaught Error: Call to undefined method Magento\Catalog\Model\ResourceModel\Category\Flat::validate()

namespace exampleVendor\exampleModule\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $categoryFactory;
    protected $categoryRepository;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryFactory,
        \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository
    ) {
        parent::__construct($context);
        $this->categoryFactory = $categoryFactory;
        $this->categoryRepository = $categoryRepository;
    }

    public function execute()
    {
        $categories = $this->categoryFactory->create()
            ->addAttributeToFilter('is_active', 1)
            ->addAttributeToSort('id')
            ->addAttributeToSelect('*');

        foreach ($categories as $category){
            $category->setIncludeInMenu(1);
            $this->categoryRepository->save($category);
        }
    }
}

As requested the full error message is:

Uncaught Error: Call to undefined method Magento\Catalog\Model\ResourceModel\Category\Flat::validate() in /vendor/magento/module-catalog/Model/Category.php:1077 
    Stack trace: #0 /generated/code/Magento/Catalog/Model/Category/Interceptor.php(570): Magento\Catalog\Model\Category->validate() 
    #1 /vendor/magento/module-catalog/Model/CategoryRepository.php(194): Magento\Catalog\Model\Category\Interceptor->validate() 
    #2 /vendor/magento/module-catalog/Model/CategoryRepository.php(112): Magento\Catalog\Model\CategoryRepository->validateCategory(Object(Magento\Catalog\Model\Category\Interceptor)) 
    #3 /generated/code/Magento/Catalog/Model/CategoryRepository/Interceptor.php(24): Magento\Catalog\Model\CategoryRepository->save(Object(Magento\Catalog\Model\Category\Interceptor)) 
    #4 /app/code/exampleVendor/exampleModule/Controller in /vendor/magento/module-catalog/Model/Category.php on line 1077
Was it helpful?

Solution

1/ You must change the scope inside your custom module routes.xml

<?xml version="1.0" encoding="utf-8"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd"> <router id="admin"> <route id="yourRouteId" frontName="yourRouteUrl"> <module name="yourModulename" /> </route> </router> </config>

2/ Your controller will now extend backend : class Index extends \Magento\Backend\App\Action

3/ Run this page from your admin, you must be logged in inside your Magento back office.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top