I would like to set my ID on the category Category::setId but this results in the following exception: "No such entity with id = x".

My code:

$catFactory = $objectManager->get(CategoryFactory::class);
$catRepo = $objectManager->get(CategoryRepositoryInterface::class);
$cat = $catFactory->create();

Thank you.


You can not set category id by yourself while creating category programatically. It will be generated by magento it-self because it is primary key and associated at many place in database. So category id create thing will manage by magento code code.

So remove line from your code:


You can use below code for create category programatically:

use \Magento\Framework\App\Bootstrap;

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$url = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $url->get('\Magento\Store\Model\StoreManagerInterface');
$mediaurl= $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$state = $objectManager->get('\Magento\Framework\App\State');
/// Get Website ID
$websiteId = $storeManager->getWebsite()->getWebsiteId();
echo 'websiteId: '.$websiteId." ";

/// Get Store ID
$store = $storeManager->getStore();
$storeId = $store->getStoreId();
echo 'storeId: '.$storeId." ";

/// Get Root Category ID
$rootNodeId = $store->getRootCategoryId();
echo 'rootNodeId: '.$rootNodeId." ";
/// Get Root Category
$rootCat = $objectManager->get('Magento\Catalog\Model\Category');
$cat_info = $rootCat->load($rootNodeId);

$categorys=array('Levis','Wranglers','Basics'); // Category Names
foreach($categorys as $cat)

$cleanurl = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($url))))));
/// Add a new sub category under root category
$categoryTmp = $categoryFactory->create();
$categoryTmp->setData('description', 'description');
$mediaAttribute = array ('image', 'small_image', 'thumbnail');
$categoryTmp->setImage('/m2.png', $mediaAttribute, true, false);// Path pub/meida/catalog/category/m2.png

Reference : https://vinothkumaarr.wordpress.com/2016/05/13/add-multiple-category-programmatically-magento2/

| improve this answer | |

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.