0

I'm using this function to create categories

public function fetchOrCreateProductCategory($categoryName, $parentId = 1)
{
    //when parent id is 1, then it's root category
    $parentCategory = $this->categoryFactory->create()->load($parentId);

    $category = $this->categoryFactory->create();
    $cate = $category->getCollection()
        ->addAttributeToFilter('name', $categoryName)
        ->getFirstItem();

    if (!$cate->getId()) {
        var_dump('in');
        $category->setPath($parentCategory->getPath())
            ->setParentId($parentId)
            ->setName($categoryName)
            ->setIsActive(true);
        var_dump('in 2');
        $category->save();
    }
    var_dump('end');
    return $category;
}

Then I call it

$rootCategory = $this->fetchOrCreateProductCategory('Default Pro Category');

It works

Then I call it with a sub category

$subCat1 = $this->fetchOrCreateProductCategory('Cofee',$rootCategoryId);

And here it fails right after

in 2

with the message

Area code is not set

Obviously something is wrong when I try to save a subcategory...but I can't figure it what is it.

4

use this class please:

<?php
declare(strict_types=1);
namespace here;
use Magento\Framework\App\State;

class SetAreaCode
{
    /**
     * @var State
     */
    private $state;

    /**
     * @param State $state
     */
    public function __construct(
        State $state
    ) {
        $this->state = $state;
    }

    /**
     * @param string $areaCode
     * @return void
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function execute(string $areaCode): void
    {
        try {
            $this->state->getAreaCode();
        } catch (\Exception $e) {
            $this->state->setAreaCode($areaCode);
        }
    }
}

this is your class:

public function fetchOrCreateProductCategory($categoryName, $parentId = 1)
{
    $this->setAreaCode->execute('adminhtml');

    //when parent id is 1, then it's root category
    $parentCategory = $this->categoryFactory->create()->load($parentId);

    $category = $this->categoryFactory->create();
    $cate = $category->getCollection()
        ->addAttributeToFilter('name', $categoryName)
        ->getFirstItem();

    if (!$cate->getId()) {
        var_dump('in');
        $category->setPath($parentCategory->getPath())
            ->setParentId($parentId)
            ->setName($categoryName)
            ->setIsActive(true);
        var_dump('in 2');
        $category->save();
    }
    var_dump('end');
    return $category;
}

Cheers

| 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.