I'm trying to create new categories. My code, which is called in the admin panel, looks this way:

/** @var \Magento\Catalog\Api\Data\CategoryInterface $parentCategory */
/** @var \Magento\Catalog\Api\Data\CategoryInterfaceFactory $this->categoryFactory */
/** @var \Magento\Catalog\Api\CategoryRepositoryInterface $this->categoryRepository */
$data = [
    'parent_id' => $parentCategory->getEntityId(),
    'name' => ucwords(strtolower($name)),
    'is_active' => 1,
    'is_anchor' => 0,
    'include_in_menu' => 1,
    'url_key' => strtolower(str_replace(' ', '-', $name)),
    'display_mode' => 'PAGE',
    'page_layout' => '1column'
$category = $this->categoryFactory->create();

Although categories created this way do get created, all the data is being added for store_id 1 instead of 0. Because of this, my categories lack name (among other stuff) when seen on the category listing in the admin panel.

What I tried:

  • Setting the store_id on a category before saving it (it was just a blind guess, not a result of any research), like this: $category->setStoreId(0)->setData($data)

  • Emulating area code in a similar way it's done in sample data modules, this way:

    /** @var \Magento\Framework\App\State $this->appState */
            [$this, 'getCategory'],
            ['name' => $name, 'parentCategory' => $parentCategory]

    where getCategory is a method wrapping up the code pasted at the beginning of the post.

None of those methods succeeded, though. What do I miss?


Figured that out already. The following code needs to be placed before the code that creates a category:


In case someone else has the same problem and doesn't know this, the storeManager property needs to be included in the construct, like everything else, this way:

public function __construct(
    // all the other stuff you need here
    \Magento\Store\Model\StoreManagerInterface $storeManager
) {
    // all the other stuff you need here
    $this->storeManager = $storeManager;

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.