Friday, 20 December 2019

Magento 2 How to duplicate the category with same structure?

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();
    }
You can also check more Magento related Question/Answers here

No comments:

Post a Comment

about new GraphQL freature in Magento2

GraphQL: GraphQL is a data query language developed internally by Facebook in 2012 before being publicly released in 2015. Magento impleme...