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();
}