0

I am trying below code to update category name and parent id by categoryId,

 public function __construct(
    \Magento\Catalog\Model\CategoryFactory $categoryFactory

) { 
    $this->categoryFactory = $categoryFactory;      

}
 $catId = 5;
$name = 'test';
try {
   $category = $this->categoryFactory->create()->setStoreId(1)->load($catId);
   $category->setName($name);
   $category->save();
  echo "Category is updated successfully";
}
catch (Exception $e) {
        print_r($e->getMessage());
}

But category name is not updating for me. Where i am wrong please anyone suggest me

  • Have you checked value for correct store id after saving? – Mohit Kumar Arora Sep 10 '18 at 13:29
0

We need to identify the id of category tree root. Then, we created an instance of the category, set its path, parent_id, name, etc.

$parentId = \Magento\Catalog\Model\Category::TREE_ROOT_ID;

$parentCategory = $this->_objectManager
                      ->create('Magento\Catalog\Model\Category')
                      ->load($parentId);
$category = $this->_objectManager
                ->create('Magento\Catalog\Model\Category');
//Check exist category
$cate = $category->getCollection()
            ->addAttributeToFilter('name','test')
            ->getFirstItem();

if(!isset($cate->getId())) {
    $category->setPath($parentCategory->getPath())
        ->setParentId($parentId)
        ->setName('test')
        ->setIsActive(true);
    $category->save();
}

You can try this it's working fine for me.

  • is it possible to update with category id? – jafar pinjar Sep 10 '18 at 13:25
  • Let me first try and let you know. – Dharmendra Jadav Sep 10 '18 at 13:27
  • Ok try once, please update me once it is worked for you – jafar pinjar Sep 10 '18 at 14:34

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.