2

I am working on duplicate category, In my controller file, I am able to duplicate the category but I need to assign the same products to the newly created category from the old one.

i.e. I have the category name "Abc" has 10 products and 2 of them are In-stock / out of stock / disable, now I duplicate the category with and the new name is "Xyz". I want to assign all 10 products into "Xyz".

How could I achieve this functionality?

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();
}
2
  • Can you please upload your code logic which you have done? Commented Jul 19, 2019 at 6:35
  • Use this extension instead if you are OK with it. It will make your life easier with duplicating categories. Commented Jan 16, 2020 at 9:59

1 Answer 1

0

When possible I would try to use APIs for interacting with the Magento core.

Consider using:

use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\Data\CategoryInterfaceFactory;
use Magento\Catalog\Api\CategoryLinkManagementInterface;
use Magento\Catalog\Api\Data\CategoryInterfaceFactory;
use Magento\Catalog\Api\ProductRepositoryInterface

The duplicate product assignment might look something like

$categoryProductLinks = $this->categoryLinkManagement
    ->getAssignedProducts($sourceCategory->getId());

/** @var \Magento\Catalog\Api\Data\CategoryProductLinkInterface $categoryProductLink */
foreach ($categoryProductLinks as $categoryProductLink) {
    $product = $this->productRepository->get($categoryProductLink->getSku());
    $categoryIds = $product->getCategoryIds();
    array_push($categoryIds, $newCategory->getId());
    $this->categoryLinkManagement
         ->assignProductToCategories($product->getSku(), $categoryIds);
}

Note:

  • Above is just an example of an idea and not tested code.
  • While productRepository->get returns \Magento\Catalog\Api\Data\ProductInterface the underlying object \Magento\Catalog\Model\Product has getCategoryIds()

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.