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

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

            Circuit construction for execution of conditional statements using least significant bitHow are two different registers being used as “control”?How exactly is the stated composite state of the two registers being produced using the $R_zz$ controlled rotations?Efficiently performing controlled rotations in HHLWould this quantum algorithm implementation work?How to prepare a superposed states of odd integers from $1$ to $sqrtN$?Why is this implementation of the order finding algorithm not working?Circuit construction for Hamiltonian simulationHow can I invert the least significant bit of a certain term of a superposed state?Implementing an oracleImplementing a controlled sum operation

            Magento 2 “No Payment Methods” in Admin New OrderHow to integrate Paypal Express Checkout with the Magento APIMagento 1.5 - Sales > Order > edit order and shipping methods disappearAuto Invoice Check/Money Order Payment methodAdd more simple payment methods?Shipping methods not showingWhat should I do to change payment methods if changing the configuration has no effects?1.9 - No Payment Methods showing upMy Payment Methods not Showing for downloadable/virtual product when checkout?Magento2 API to access internal payment methodHow to call an existing payment methods in the registration form?