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();
}
  • Can you please upload your code logic which you have done? – Rohan Hapani Jul 19 at 6:35
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, privacy policy and cookie policy

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