Magento 2 How to duplicate category products into another categoryImport new categories via CSV and assign categories to existing products by SKUI created a custom module ,but getting error, not able to figure out what the error is about. How to get out of this error?Magento 2.1: Invoke urlBuilder->getUrl() in a controller in a custom moduleMagento 2: Products with internal IDs > ~16500 not showing in categoryMagento2 - create new/update category programmatically for specific storeView not workingWhy Getting categories and names on product view page Magento 2 fails?Price not getting updated for second product…Create Dirty Playground In Magento 2.1.6List Products of CategoryMagento 2 - All products page with layered navigation and pagination

Is my employer paying me fairly? Going from 1099 to W2

Why isnt the output showing k1, k2, k3?

Weed in Massachusetts: underground roots, skunky smell when bruised

Why are so many countries still in the Commonwealth?

Timing/Stack question about abilities triggered during combat

What do I do when a student working in my lab "ghosts" me?

How can I create a pattern of parallel lines that are increasing in distance in Photoshop / Illustrator?

Inadvertently nuked my disk permission structure - why?

Trapped in an ocean Temple in Minecraft?

Why are off grid solar setups only 12, 24, 48 VDC?

Commercial jet accompanied by small plane near Seattle

Print sums of all subsets

Giant space birds hatching out of planets; short story

How do we explain the E major chord in this progression?

How can I prevent corporations from growing their own workforce?

How to deal with a player who makes bad characters and kills them?

Basic Questions on Wiener Filtering

What is the difference between 1/3, 1/2, and full casters?

Area of parallelogram = Area of square. Shear transform

Binomial analogue of Riemann sum for definite integral

How do I run a game when my PCs have different approaches to combat?

Expansion with *.txt in the shell doesn't work if no .txt file exists

Why can't my huge trees be chopped down?

This message is flooding my syslog, how to find where it comes from?



Magento 2 How to duplicate category products into another category


Import new categories via CSV and assign categories to existing products by SKUI created a custom module ,but getting error, not able to figure out what the error is about. How to get out of this error?Magento 2.1: Invoke urlBuilder->getUrl() in a controller in a custom moduleMagento 2: Products with internal IDs > ~16500 not showing in categoryMagento2 - create new/update category programmatically for specific storeView not workingWhy Getting categories and names on product view page Magento 2 fails?Price not getting updated for second product…Create Dirty Playground In Magento 2.1.6List Products of CategoryMagento 2 - All products page with layered navigation and pagination






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








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 MagentoBackendAppAction 
protected $_categoryFactory;
public function __construct(
MagentoBackendAppActionContext $context,
MagentoCatalogModelCategoryFactory $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();










share|improve this question
























  • Can you please upload your code logic which you have done?

    – Rohan Hapani
    Jul 19 at 6:35

















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 MagentoBackendAppAction 
protected $_categoryFactory;
public function __construct(
MagentoBackendAppActionContext $context,
MagentoCatalogModelCategoryFactory $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();










share|improve this question
























  • Can you please upload your code logic which you have done?

    – Rohan Hapani
    Jul 19 at 6:35













2












2








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 MagentoBackendAppAction 
protected $_categoryFactory;
public function __construct(
MagentoBackendAppActionContext $context,
MagentoCatalogModelCategoryFactory $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();










share|improve this question
















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 MagentoBackendAppAction 
protected $_categoryFactory;
public function __construct(
MagentoBackendAppActionContext $context,
MagentoCatalogModelCategoryFactory $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();







magento2 magento-2.1 category magento2.3 category-products






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 19 at 9:26







Utsav Gupta

















asked Jul 17 at 12:25









Utsav GuptaUtsav Gupta

5492 silver badges16 bronze badges




5492 silver badges16 bronze badges












  • Can you please upload your code logic which you have done?

    – Rohan Hapani
    Jul 19 at 6:35

















  • Can you please upload your code logic which you have done?

    – Rohan Hapani
    Jul 19 at 6:35
















Can you please upload your code logic which you have done?

– Rohan Hapani
Jul 19 at 6:35





Can you please upload your code logic which you have done?

– Rohan Hapani
Jul 19 at 6:35










1 Answer
1






active

oldest

votes


















0














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



Consider using:



use MagentoCatalogApiCategoryRepositoryInterface;
use MagentoCatalogApiDataCategoryInterfaceFactory;
use MagentoCatalogApiCategoryLinkManagementInterface;
use MagentoCatalogApiDataCategoryInterfaceFactory;
use MagentoCatalogApiProductRepositoryInterface


The duplicate product assignment might look something like



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

/** @var MagentoCatalogApiDataCategoryProductLinkInterface $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
    MagentoCatalogApiDataProductInterface the underlying object
    MagentoCatalogModelProduct has getCategoryIds()





share|improve this answer

























    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "479"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f282391%2fmagento-2-how-to-duplicate-category-products-into-another-category%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














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



    Consider using:



    use MagentoCatalogApiCategoryRepositoryInterface;
    use MagentoCatalogApiDataCategoryInterfaceFactory;
    use MagentoCatalogApiCategoryLinkManagementInterface;
    use MagentoCatalogApiDataCategoryInterfaceFactory;
    use MagentoCatalogApiProductRepositoryInterface


    The duplicate product assignment might look something like



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

    /** @var MagentoCatalogApiDataCategoryProductLinkInterface $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
      MagentoCatalogApiDataProductInterface the underlying object
      MagentoCatalogModelProduct has getCategoryIds()





    share|improve this answer



























      0














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



      Consider using:



      use MagentoCatalogApiCategoryRepositoryInterface;
      use MagentoCatalogApiDataCategoryInterfaceFactory;
      use MagentoCatalogApiCategoryLinkManagementInterface;
      use MagentoCatalogApiDataCategoryInterfaceFactory;
      use MagentoCatalogApiProductRepositoryInterface


      The duplicate product assignment might look something like



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

      /** @var MagentoCatalogApiDataCategoryProductLinkInterface $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
        MagentoCatalogApiDataProductInterface the underlying object
        MagentoCatalogModelProduct has getCategoryIds()





      share|improve this answer

























        0












        0








        0







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



        Consider using:



        use MagentoCatalogApiCategoryRepositoryInterface;
        use MagentoCatalogApiDataCategoryInterfaceFactory;
        use MagentoCatalogApiCategoryLinkManagementInterface;
        use MagentoCatalogApiDataCategoryInterfaceFactory;
        use MagentoCatalogApiProductRepositoryInterface


        The duplicate product assignment might look something like



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

        /** @var MagentoCatalogApiDataCategoryProductLinkInterface $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
          MagentoCatalogApiDataProductInterface the underlying object
          MagentoCatalogModelProduct has getCategoryIds()





        share|improve this answer













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



        Consider using:



        use MagentoCatalogApiCategoryRepositoryInterface;
        use MagentoCatalogApiDataCategoryInterfaceFactory;
        use MagentoCatalogApiCategoryLinkManagementInterface;
        use MagentoCatalogApiDataCategoryInterfaceFactory;
        use MagentoCatalogApiProductRepositoryInterface


        The duplicate product assignment might look something like



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

        /** @var MagentoCatalogApiDataCategoryProductLinkInterface $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
          MagentoCatalogApiDataProductInterface the underlying object
          MagentoCatalogModelProduct has getCategoryIds()






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jul 19 at 12:00









        Ian at XantekIan at Xantek

        2931 silver badge8 bronze badges




        2931 silver badge8 bronze badges



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Magento Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f282391%2fmagento-2-how-to-duplicate-category-products-into-another-category%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

            Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

            Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form