I tried importing a single product in magento 2..It failed..
I tried a script in magento 2 root directory and
My code is
<?php
use MagentoFrameworkAppBootstrap;
require __DIR__ . '/app/bootstrap.php';
$params = $_SERVER;
$params[Bootstrap::PARAM_REQUIRE_MAINTENANCE] = true; // default false
$params[Bootstrap::PARAM_REQUIRE_IS_INSTALLED] = false; // default true
$bootstrap = Bootstrap::create(BP, $params);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('MagentoFrameworkAppState');
$state->setAreaCode('frontend');
$simple_product = $objectManager->create('MagentoCatalogModelProduct');
$simple_product->setSku('Tops');
$simple_product->setName('tops');
$simple_product->setAttributeSetCode('Default');
$simple_product->setCategories('Default Category/Women');
$simple_product->setStatus(1);
$simple_product->setTypeId('simple');
$simple_product->setPrice(10);
$simple_product->setProductWebsites('base');
$simple_product->setCategoryIds(array(31));
$simple_product->setUrlKey ('tops');
$simple_product->setColor('Red');
$simple_product->setStockData(array(
'use_config_manage_stock' => 0, //'Use config settings' checkbox
'manage_stock' => 1, //manage stock
'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
'is_in_stock' => 1, //Stock Availability
'qty' => 100 //qty
)
);
$simple_product->save();
$simple_product_id = $simple_product->getId();
echo "simple product id: ".$simple_product_id."n";
?>
and i am getting the following error
Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`magento`.`catalog_product_entity`, CONSTRAINT `CAT_PRD_ENTT_ATTR_SET_ID_EAV_ATTR_SET_ATTR_SET_ID` FOREIGN KEY (`attribute_set_id`) REFERENCES `eav_attribute_set` (`attribute_set_id`) ON DELET) in /var/www/html/magento/vendor/magento/zendframework1/library/Zend/Db/Statement/Pdo.php:228 Stack trace: #0 /var/www/html/magento/vendor/magento/zendframework1/library/Zend/Db/Statement/Pdo.php(228): PDOStatement->execute(Array) #1 /var/www/html/magento/vendor/magento/framework/DB/Statement/Pdo/Mysql.php(95): Zend_Db_Statement_Pdo->_execute(Array) #2 /var/www/html/magento/vendor/magento/zendframework1/library/Zend/Db/Statement.php(303): MagentoFrameworkDBStatementPdoMysql->_execute(Array) #3 /var/www/html/magento/vendor/magento/zendframework1/library/Zend/Db/Adapter/Abstract.php(480): Zend_Db_Statement->execute(Array) #4 /var/www/html/magento/vendor/magento/zendframework1/ in /var/www/html/magento/vendor/magento/zendframework1/library/Zend/Db/Statement/Pdo.php on line 235
Can anyone give me a solution?
4
Answers
This is the updated version of your code. Please use this code to create product.
Thanks
For Simple Product Working on M2
For configurable product working on M2