1

I am trying to create and delete categories in Magento 2 but am facing some issues while doing it when Flat Categories option is enabled.

The weird thing is, my code works fine when called from a bootstrap file like this.

<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode(\Magento\Framework\App\Area::AREA_FRONTEND);
$registry = $obj->get('\Magento\Framework\Registry');
$registry->register("isSecureArea", true);



$category = $obj->create('\Magento\Catalog\Model\CategoryFactory')->create();
$data = ['name'=>'Test', 'url_key'=> 'test'];
$parentId = 52;
$parent = $categoryFactory->create()->load($parentId);
$category = $categoryFactory->create();
$category->setData($data);
$category->addData([
    'parent_id' => $parentId,
    'path' => $parent->getPath(),
    'default_sort_by' => 'position',
    'display_mode' => \Magento\Catalog\Model\Category::DM_PRODUCT,
    'include_in_menu' => 0,
    'is_anchor' => 1
]);
$category->setStoreId(0)->save();

die('<br>done');

But when I execute the same code form a custom API controller, it fails with the following error while calling $category->save() when storeId is set to 0.

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'm23.catalog_category_flat' doesn't exist, query was: SELECT `catalog_category_flat`.* FROM `catalog_category_flat` WHERE (`catalog_category_flat`.`entity_id`='52')

If I set storeId to 1 then I get this error

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

I solved a similar issue in Magento 1.9 by using this

$category = Mage::getModel('catalog/category', array('disable_flat' => true));

Any idea how to solve this in Magento 2? :/

Thanks

0

I myself found a workaround for this problem.

Rather than creating and saving categories from your custom controller, you can use the REST API that comes with Magento 2 to do the job for you.

List of available endpoints

There is even a cool interface that comes with all Magento installations where you can play around with it. It can be found in http://<your_magento_root>/swagger. Online version

But to create a category using the REST API, you have to create a Magento integration. Which can be created in System > Extensions > Integrations. Just enter a name and your admin password and select the catalog category permissions from the API section and save it.

After doing that you'll have to click on Activate, which gives you an Access Token. Paste that Token in the input box in swagger you can now play around with it.

Hope this helps others with a similar problem :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.