0

please help Magento version 2.0.9 I am trying to add categories programmatically . And here my code

    $categoryFactory=self::getObjectManager()->get('\Magento\Catalog\Model\CategoryFactory');
    $categoryTmp = $categoryFactory->create();
    $categoryObj = $categoryTmp->load((int)$categoryDTO->getParentId());
    $categoryTmp = self::getObjectManager()->create('Magento\Catalog\Model\Category');
    $categoryTmp->setPath($categoryObj->getPath())
        ->setParentId((int)$categoryObj->getId())
        ->setName($categoryDTO->getDescription())
        ->setUrlKey($categoryDTO->getUrlKey())
        ->setIsActive(true);
    $createdCategoryId = $categoryTmp->save()      

Which is working and at some point I get

 Fatal error: Uncaught PDOException: SQLSTATE[08004] [1040] Too many connections

But I got categories (not all ) added to magento database with parent-child relationship. After refreshing page it inserts all categories (there is not much left after) ,I am trying to get rid of annoying error so I followed this link this link which is working but again at some poing I get connection error **Besides no category is added to database **. Any tip is welcomed

EDIT 1

  self::getObjectManager()

is this function

 protected static $cachedObjectManager;

public static function getObjectManager()
{
    if(!self::$cachedObjectManager){
        $bootstrap = Bootstrap::create(BP, $_SERVER);
        return $bootstrap->getObjectManager();
    }

    return self::$cachedObjectManager;
}
0

Looks like you do not store OM in static field

if(!self::$cachedObjectManager){
    $bootstrap = Bootstrap::create(BP, $_SERVER);
    return $bootstrap->getObjectManager();
}

replace it with

if(!self::$cachedObjectManager){
    $bootstrap = Bootstrap::create(BP, $_SERVER);
    return self::$cachedObjectManager = $bootstrap->getObjectManager();
}

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.