Skip to content
Advertisement

Which file should I use when assigning products to a category in Magento programatically?

I am new to Magento. I have created a category in the back end of Magento. There are quite few threads about how to assign a product to a category, however I don’t understand which file should I use to use that code:

If I understand correctly, the page is generated automatically by Magento, when you create a category and assign products to it. I know there is a view.phtml file which is a template of how the webpage should look like. Thank you in advance, guys. Will be waiting for your respond.

Advertisement

Answer

Almost eight years have passed since I’ve asked this question. I see now how bad the question is. I should have explained what I want in the first place; and now I can’t even recall.

This is how I would approach the problem:

  1. Create a service class that assigns products to the category. Perhaps create an interface that takes the product entity or the product ID as the first argument, and a category ID as the second.
  2. Reference that service class in another place depending on when I want that population to happen. There are many places:
    1. Controller (either FE or BE) action (perhaps a button)
    2. Data Patch or Install Script (to make sure the changes exist in any environment)
    3. Console command (if desired to execute via bin/magento command)
    4. Cron script, if needs to be a recurring operation
    5. Observer or a plugin if needs to happen when some specific event occurs.
    6. API request, if needed to be triggered from the outside of Magento.

I wasn’t aware of these things back in the day. And I wish I would have received this answer back then. I hope it helps other developers who start with the framework and don’t know how to structure the app.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement