2

How can I programmatically change the value of 'parent_id' in Magento 2?

I tried so far:

$category = $this->_objectManager->get('\Magento\Catalog\Model\Category')->load($id);
$d["entity_id"] = $id;
$d["name"] = $name;
$d["store_id"] = 0;
$d["parent_id"] = 7;
$category->setData($d);
$category->setStoreId(0);
$category->save();

Everything is saved except parent_id

1 Answer 1

4

Have a look at the move function in \Magento\Catalog\Model\Category.

/**
 * Move category
 *
 * @param  int $parentId new parent category id
 * @param  null|int $afterCategoryId category id after which we have put current category
 * @return $this
 * @throws \Magento\Framework\Exception\LocalizedException|\Exception
 */
public function move($parentId, $afterCategoryId)

So you have to use something like this: $category->move($newParentId, null);

1
  • 1
    Works like a charm for me. Commented Jan 22, 2020 at 8:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.