2


How to create new object Product ?
Example:

$product = new Product();
$product->sku = 'fdfds';
...
$product->save();
2
  • in which file are u performing this change ? Apr 14, 2016 at 6:40
  • I would like to apply for running file batch: app/code/myPool/Batch/Console/Command/batch.php
    – MrTo-Kane
    Apr 14, 2016 at 6:42

3 Answers 3

1

Note: This is a quick dirty code, use dependency instead.

Here is example how to create product model object :

<?php 
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); manager
 $product = $objectManager->create('\Magento\Catalog\Model\Product');
 $product->setSku('sku'); // Set your sku here
 $product->save();
?>

Another example : You can use it like create a file on root example.php and save the below code:

<?php
use Magento\Framework\App\Bootstrap;
include('app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');


$_product = $objectManager->create('Magento\Catalog\Model\Product');
$_product->setName('Test Product');
$_product->setTypeId('simple');
$_product->setAttributeSetId(4);
$_product->setSku('test-SKU');
$_product->save();
?>
3
  • 5
    Object manager must not be used directly
    – Anton Kril
    Apr 14, 2016 at 6:58
  • 1
    It is recommended to use dependency injection rather than directly using object Manager Apr 14, 2016 at 7:08
  • also for products, one should always use the Factory classes instead of using the direct model classes. Jun 22, 2018 at 4:21
6

This is a very old question, but the selected answer is completly wrong.

The answer from Manashvi Birla is kind of good but it has 2 problems

  1. He says he is using factory but infact he is not
  2. A product model should not save itself, the respository should do it. I think using save function on product model is even deprecated.

If you wish to use factory on product model class, you will have to do the following

/**
     * SaveProduct constructor.
     * @param \Magento\Catalog\Model\ProductFactory $product
     * @param \Magento\Catalog\Model\ProductRepository $productRepository
     */
    public function __construct(
        \Magento\Catalog\Model\ProductFactory $product,
        \Magento\Catalog\Model\ProductRepository $productRepository
    ) {
        $this->product = $product->create();
        $this->productRepository = $productRepository;
    }
<?php
class SaveProduct
{
    private $product;
    private $productRepository;

    /**
     * SaveProduct constructor.
     * @param \Magento\Catalog\Model\Product $product
     * @param \Magento\Catalog\Model\ProductRepository $productRepository
     */
    public function __construct(
        \Magento\Catalog\Model\Product $product,
        \Magento\Catalog\Model\ProductRepository $productRepository
    ) {
        $this->product = $product;
        $this->productRepository = $productRepository;
    }

    /**
     * @throws \Magento\Framework\Exception\CouldNotSaveException
     * @throws \Magento\Framework\Exception\InputException
     * @throws \Magento\Framework\Exception\StateException
     */
    public function execute(): void
    {
        // example product defination
        $this->product->setSku('test-simple');
        $this->product->setName('test name simple');
        $this->product->setAttributeSetId(4);
        $this->product->setSize_general(193);
        $this->product->setStatus(1);
        $this->product->setTypeId('simple');
        $this->product->setPrice(10);
        $this->product->setWebsiteIds([1]);
        $this->product->setCategoryIds([31]);

        // repository saves product
        $this->productRepository->save($this->product);
    }
}

Factories are well explained on this article http://rosenborgsolutions.com/articles/magento/magento-new-class-instance

2
  • Your solution worked like a charm. I was overriding the core Braintree Config related issue that is cropping up in Magento 2.4.x and wanted a clean solution. Thank you!
    – Shivani
    Dec 24, 2020 at 16:24
  • should be accepted answer! still working perfect in 2023
    – y.y
    Feb 3 at 12:10
5

It is recommended to use dependency injection rather than directly using object Manager. Example: In your controller file you can use following code :

protected $_product;

public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\Product $productFactory,
        array $data = []
    ) {
        $this->_product = $productFactory;
        parent::__construct($context, $data);
    }


public function execute()
{
   $this->_product->setSku('test-simple');
    $this->_product->setName('test name simple');
    $this->_product->setAttributeSetId(4);
    $this->_product->setSize_general(193); 
    $this->_product->setStatus(1);
    $this->_product->setTypeId('simple');
    $this->_product->setPrice(10);
    $this->_product->setWebsiteIds(array(1));
    $this->_product->setCategoryIds(array(31));
    $this->_product->setStockData(array(
        'use_config_manage_stock' => 0, 
        'manage_stock' => 1, 
        'min_sale_qty' => 1, 
        'max_sale_qty' => 2, 
        'is_in_stock' => 1, 
        'qty' => 100 
        )
    ); 
    $this->_product->save();
}
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.