1

I am a new Magento 2 user and I'm trying to develop a plugin, but iv been stuck on this problem for the past 2 days. I am trying to programmatically add a new product to the Magento 2 database. For this, I figured out I need to inject de product factory dependency to my custom plugin but I have no clue how to do this. I see there is a di.xml file in most plugins so I'm guessing this stands for Dependency Injection and I need to add the relevant code here but have no idea as to how to do this.

I am trying to use the product factory in Controller/Adminhtml/Index/Index.php, this is my directory structure:

My Dir Structure

What do I need to write in di.xml to be able to get this dependency in Index's constructor?

This is my Index.php code:

        <?php

        namespace Sunoptic\Koppeling\Controller\Adminhtml\Index;

        use Magento\Framework\Controller\ResultFactory;

        class Index extends \Magento\Backend\App\Action
        {
            private $_productFactory;
            private $_productRepository;

            public function __construct(\Magento\Backend\App\Action\Context $context, \Magento\Catalog\Api\Data\ProductInterfaceFactory $productFactory)
            {
                parent::__construct($context);
                $this->_productFactory = $productFactory;
            }

            public function execute()
            {
                /** @var \Magento\Framework\Controller\Result\Raw $result */
                $result = $this->resultFactory->create(ResultFactory::TYPE_RAW);
                $string = "";

                $result->setContents($string);
                return $result;
            }
        }

This returns error 500 probably because of the dependency problem.

I expect this error but have no clue how to actually add this dependancy.

Michael Guimaraes
  • 333
  • 1
  • 3
  • 20

1 Answers1

0

Run Below command

php bin/magento setup:di:compile

you need to Run this command every time new dependency is injected to any class through class or di.xml.

open debug mode so you can see error in any case.

php bin/magento setup:debug:mode developer
Dexture
  • 976
  • 1
  • 11
  • 29