4

I want to duplicate the category with the same structure and data.

How to duplicate child categories here? It is working correctly for a single category.

In my controller file, I have the parent category id and category id which needs to duplicate. Now how can I create duplication of a category?

Please check my code is as below:

class DuplicateCategory extends \Magento\Backend\App\Action {
protected $_categoryFactory;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Catalog\Model\CategoryFactory $categoryFactory
) {
parent::__construct($context);
$this->_categoryFactory = $categoryFactory;
}

$parentCategoryObj = $this->_categoryFactory->create()->load(2);
$duplicateCategoryObj = $this->_categoryFactory->create()->load(8);
$catagoryObject = $this->_categoryFactory->create();

$categoryName = $duplicateCategoryObj->getName();
$categoryUrlKey = strtolower($this->getCategoryUrlKey($categoryName));

$catagoryObject->setPath($parentCategoryObj->getPath())
->setParentId($parentCategory)
->setName($duplicateCategoryObj->getName())
->setUrlKey($categoryUrlKey)
->setStoreId($storeId)
->setIsActive(true);
$catagoryObject->save();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.