2


How to create new object Product ?
Example:

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

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();
?>
  • 5
    Object manager must not be used directly – Anton Kril Apr 14 '16 at 6:58
  • 1
    It is recommended to use dependency injection rather than directly using object Manager – Manashvi Birla Apr 14 '16 at 7:08
  • also for products, one should always use the Factory classes instead of using the direct model classes. – Zeeshan Khuwaja Jun 22 '18 at 4:21
6

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();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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