Assign Inventory source while programmatically creating product












0















I have a custom script that read csv and create products programmatically, it was working fine with Magento 2.2.6, now I upgraded it to Magento 2.3, and with upgradation I configured Multi Source Inventory. The issue I am facing is that while saving the product it is throwing error "The stock item was unable to be saved. Please try again."



I am getting below error in log



 main.CRITICAL: The stock item was unable to be saved. Please try again. {"exception":"[object] (Magento\Framework\Exception\CouldNotSaveException(code: 0): The stock item was unable to be saved. Please try again. at /magento_root/vendor/magento/module-catalog-inventory/Model/Stock/StockItemRepository.php:187,
Magento\Framework\Exception\CouldNotSaveException(code: 0): Could not save Source Item at /magento_root/vendor/magento/module-inventory/Model/SourceItem/Command/Handler/SourceItemsSaveHandler.php:78,
Zend_Db_Statement_Exception(code: 23000): SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`magento_db`.`inventory_source_item`, CONSTRAINT `INVENTORY_SOURCE_ITEM_SOURCE_CODE_INVENTORY_SOURCE_SOURCE_CODE` FOREIGN KEY (`source_code`) REFERENCES `inventory_source` (`source_code`) ON DEL), query was: INSERT INTO inventory_source_item (`source_code`, `sku`, `quantity`, `status`) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE `quantity` = VALUES(`quantity`), `status` = VALUES(`status`) at /magento_root/vendor/magento/zendframework1/library/Zend/Db/Statement/Pdo.php:235,
PDOException(code: 23000): SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`magento_db`.`inventory_source_item`, CONSTRAINT `INVENTORY_SOURCE_ITEM_SOURCE_CODE_INVENTORY_SOURCE_SOURCE_CODE` FOREIGN KEY (`source_code`) REFERENCES `inventory_source` (`source_code`) ON DEL) at /magento_root/vendor/magento/zendframework1/library/Zend/Db/Statement/Pdo.php:228)"}


I am using below code to create product programmatically, injected MagentoCatalogModelProductFactory $productFactory, creating product as below



$_product = $this->_productFactory->create();

$mainImage = "";
$imagesToImport = "";
if (isset($productData['images'])) {
$images = explode(',', $productData['images']);
$mainImage = $images[0];
array_shift($images);
if (count($images) > 0) {
if (count($images) > 1) {
$imagesToImport = implode(';', $images);
} else {
$imagesToImport = $images[0];
}
}
}
$urlKey = $this->geturlKey($productData['name']);
$_product->setName($productData['name']);
$_product->setTypeId('simple');
$_product->setAttributeSetId(4);
$_product->setCategoryIds($this->getCategoryId($productData['category']));
$_product->setSku($productData['sku']);
$_product->setStatus(2);
$_product->setUrlKey(strtolower($urlKey) . '-' . $productData['sku']);
$_product->setWebsiteIds(array(1));
$_product->setVisibility(4);
$_product->setDescription($productData['description']);
$_product->setShortDescription($productData['short_description']);
$_product->setPrice($productData['price']);
if (isset($productData['special_price'])) {
$_product->setSpecialPrice($productData['special_price']);
$_product->setSpecialFromDate(''); //special price from (MM-DD-YYYY)
$_product->setSpecialToDate(''); //special price to (MM-DD-YYYY)
}
$_product->setMetaTitle($productData['meta_title']);
$_product->setMetaKeyword($productData['meta_keyword']);
if (!empty($productData['tier_price'])) {
$_product->setTierPrices($productData['tier_price']);
}
$_product->setWeight($productData['weight']);
$_product->setMetaDescription($productData['meta_description']);
$_product->setTaxClassId($productData['tax_class_id']);
$shoeColorId = $this->_eavAttribute->getIdByCode('catalog_product', 'color');
$shoeBrandId = $this->_eavAttribute->getIdByCode('catalog_product', 'manufacturer');
$_product->setColor($this->getAttributeOptionId($productData['color'], $shoeColorId, 'color'));
$_product->setManufacturer($this->getAttributeOptionId($productData['manufacturer'], $shoeBrandId, 'manufacturer'));
$_product->setStockData(
array(
'use_config_manage_stock' => 0, //'Use config settings' checkbox
'manage_stock' => 1, //manage stock
'is_in_stock' => $productData['is_in_stock'], //Stock Availability
'qty' => $productData['stock'], //qty
)
);
$_product->save();


The issue with code is missing inventory source details, I am looking for a way to create product programmatically and assigning the source at same time .



How can I create product programmatically with proper inventory management?










share|improve this question



























    0















    I have a custom script that read csv and create products programmatically, it was working fine with Magento 2.2.6, now I upgraded it to Magento 2.3, and with upgradation I configured Multi Source Inventory. The issue I am facing is that while saving the product it is throwing error "The stock item was unable to be saved. Please try again."



    I am getting below error in log



     main.CRITICAL: The stock item was unable to be saved. Please try again. {"exception":"[object] (Magento\Framework\Exception\CouldNotSaveException(code: 0): The stock item was unable to be saved. Please try again. at /magento_root/vendor/magento/module-catalog-inventory/Model/Stock/StockItemRepository.php:187,
    Magento\Framework\Exception\CouldNotSaveException(code: 0): Could not save Source Item at /magento_root/vendor/magento/module-inventory/Model/SourceItem/Command/Handler/SourceItemsSaveHandler.php:78,
    Zend_Db_Statement_Exception(code: 23000): SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`magento_db`.`inventory_source_item`, CONSTRAINT `INVENTORY_SOURCE_ITEM_SOURCE_CODE_INVENTORY_SOURCE_SOURCE_CODE` FOREIGN KEY (`source_code`) REFERENCES `inventory_source` (`source_code`) ON DEL), query was: INSERT INTO inventory_source_item (`source_code`, `sku`, `quantity`, `status`) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE `quantity` = VALUES(`quantity`), `status` = VALUES(`status`) at /magento_root/vendor/magento/zendframework1/library/Zend/Db/Statement/Pdo.php:235,
    PDOException(code: 23000): SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`magento_db`.`inventory_source_item`, CONSTRAINT `INVENTORY_SOURCE_ITEM_SOURCE_CODE_INVENTORY_SOURCE_SOURCE_CODE` FOREIGN KEY (`source_code`) REFERENCES `inventory_source` (`source_code`) ON DEL) at /magento_root/vendor/magento/zendframework1/library/Zend/Db/Statement/Pdo.php:228)"}


    I am using below code to create product programmatically, injected MagentoCatalogModelProductFactory $productFactory, creating product as below



    $_product = $this->_productFactory->create();

    $mainImage = "";
    $imagesToImport = "";
    if (isset($productData['images'])) {
    $images = explode(',', $productData['images']);
    $mainImage = $images[0];
    array_shift($images);
    if (count($images) > 0) {
    if (count($images) > 1) {
    $imagesToImport = implode(';', $images);
    } else {
    $imagesToImport = $images[0];
    }
    }
    }
    $urlKey = $this->geturlKey($productData['name']);
    $_product->setName($productData['name']);
    $_product->setTypeId('simple');
    $_product->setAttributeSetId(4);
    $_product->setCategoryIds($this->getCategoryId($productData['category']));
    $_product->setSku($productData['sku']);
    $_product->setStatus(2);
    $_product->setUrlKey(strtolower($urlKey) . '-' . $productData['sku']);
    $_product->setWebsiteIds(array(1));
    $_product->setVisibility(4);
    $_product->setDescription($productData['description']);
    $_product->setShortDescription($productData['short_description']);
    $_product->setPrice($productData['price']);
    if (isset($productData['special_price'])) {
    $_product->setSpecialPrice($productData['special_price']);
    $_product->setSpecialFromDate(''); //special price from (MM-DD-YYYY)
    $_product->setSpecialToDate(''); //special price to (MM-DD-YYYY)
    }
    $_product->setMetaTitle($productData['meta_title']);
    $_product->setMetaKeyword($productData['meta_keyword']);
    if (!empty($productData['tier_price'])) {
    $_product->setTierPrices($productData['tier_price']);
    }
    $_product->setWeight($productData['weight']);
    $_product->setMetaDescription($productData['meta_description']);
    $_product->setTaxClassId($productData['tax_class_id']);
    $shoeColorId = $this->_eavAttribute->getIdByCode('catalog_product', 'color');
    $shoeBrandId = $this->_eavAttribute->getIdByCode('catalog_product', 'manufacturer');
    $_product->setColor($this->getAttributeOptionId($productData['color'], $shoeColorId, 'color'));
    $_product->setManufacturer($this->getAttributeOptionId($productData['manufacturer'], $shoeBrandId, 'manufacturer'));
    $_product->setStockData(
    array(
    'use_config_manage_stock' => 0, //'Use config settings' checkbox
    'manage_stock' => 1, //manage stock
    'is_in_stock' => $productData['is_in_stock'], //Stock Availability
    'qty' => $productData['stock'], //qty
    )
    );
    $_product->save();


    The issue with code is missing inventory source details, I am looking for a way to create product programmatically and assigning the source at same time .



    How can I create product programmatically with proper inventory management?










    share|improve this question

























      0












      0








      0








      I have a custom script that read csv and create products programmatically, it was working fine with Magento 2.2.6, now I upgraded it to Magento 2.3, and with upgradation I configured Multi Source Inventory. The issue I am facing is that while saving the product it is throwing error "The stock item was unable to be saved. Please try again."



      I am getting below error in log



       main.CRITICAL: The stock item was unable to be saved. Please try again. {"exception":"[object] (Magento\Framework\Exception\CouldNotSaveException(code: 0): The stock item was unable to be saved. Please try again. at /magento_root/vendor/magento/module-catalog-inventory/Model/Stock/StockItemRepository.php:187,
      Magento\Framework\Exception\CouldNotSaveException(code: 0): Could not save Source Item at /magento_root/vendor/magento/module-inventory/Model/SourceItem/Command/Handler/SourceItemsSaveHandler.php:78,
      Zend_Db_Statement_Exception(code: 23000): SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`magento_db`.`inventory_source_item`, CONSTRAINT `INVENTORY_SOURCE_ITEM_SOURCE_CODE_INVENTORY_SOURCE_SOURCE_CODE` FOREIGN KEY (`source_code`) REFERENCES `inventory_source` (`source_code`) ON DEL), query was: INSERT INTO inventory_source_item (`source_code`, `sku`, `quantity`, `status`) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE `quantity` = VALUES(`quantity`), `status` = VALUES(`status`) at /magento_root/vendor/magento/zendframework1/library/Zend/Db/Statement/Pdo.php:235,
      PDOException(code: 23000): SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`magento_db`.`inventory_source_item`, CONSTRAINT `INVENTORY_SOURCE_ITEM_SOURCE_CODE_INVENTORY_SOURCE_SOURCE_CODE` FOREIGN KEY (`source_code`) REFERENCES `inventory_source` (`source_code`) ON DEL) at /magento_root/vendor/magento/zendframework1/library/Zend/Db/Statement/Pdo.php:228)"}


      I am using below code to create product programmatically, injected MagentoCatalogModelProductFactory $productFactory, creating product as below



      $_product = $this->_productFactory->create();

      $mainImage = "";
      $imagesToImport = "";
      if (isset($productData['images'])) {
      $images = explode(',', $productData['images']);
      $mainImage = $images[0];
      array_shift($images);
      if (count($images) > 0) {
      if (count($images) > 1) {
      $imagesToImport = implode(';', $images);
      } else {
      $imagesToImport = $images[0];
      }
      }
      }
      $urlKey = $this->geturlKey($productData['name']);
      $_product->setName($productData['name']);
      $_product->setTypeId('simple');
      $_product->setAttributeSetId(4);
      $_product->setCategoryIds($this->getCategoryId($productData['category']));
      $_product->setSku($productData['sku']);
      $_product->setStatus(2);
      $_product->setUrlKey(strtolower($urlKey) . '-' . $productData['sku']);
      $_product->setWebsiteIds(array(1));
      $_product->setVisibility(4);
      $_product->setDescription($productData['description']);
      $_product->setShortDescription($productData['short_description']);
      $_product->setPrice($productData['price']);
      if (isset($productData['special_price'])) {
      $_product->setSpecialPrice($productData['special_price']);
      $_product->setSpecialFromDate(''); //special price from (MM-DD-YYYY)
      $_product->setSpecialToDate(''); //special price to (MM-DD-YYYY)
      }
      $_product->setMetaTitle($productData['meta_title']);
      $_product->setMetaKeyword($productData['meta_keyword']);
      if (!empty($productData['tier_price'])) {
      $_product->setTierPrices($productData['tier_price']);
      }
      $_product->setWeight($productData['weight']);
      $_product->setMetaDescription($productData['meta_description']);
      $_product->setTaxClassId($productData['tax_class_id']);
      $shoeColorId = $this->_eavAttribute->getIdByCode('catalog_product', 'color');
      $shoeBrandId = $this->_eavAttribute->getIdByCode('catalog_product', 'manufacturer');
      $_product->setColor($this->getAttributeOptionId($productData['color'], $shoeColorId, 'color'));
      $_product->setManufacturer($this->getAttributeOptionId($productData['manufacturer'], $shoeBrandId, 'manufacturer'));
      $_product->setStockData(
      array(
      'use_config_manage_stock' => 0, //'Use config settings' checkbox
      'manage_stock' => 1, //manage stock
      'is_in_stock' => $productData['is_in_stock'], //Stock Availability
      'qty' => $productData['stock'], //qty
      )
      );
      $_product->save();


      The issue with code is missing inventory source details, I am looking for a way to create product programmatically and assigning the source at same time .



      How can I create product programmatically with proper inventory management?










      share|improve this question














      I have a custom script that read csv and create products programmatically, it was working fine with Magento 2.2.6, now I upgraded it to Magento 2.3, and with upgradation I configured Multi Source Inventory. The issue I am facing is that while saving the product it is throwing error "The stock item was unable to be saved. Please try again."



      I am getting below error in log



       main.CRITICAL: The stock item was unable to be saved. Please try again. {"exception":"[object] (Magento\Framework\Exception\CouldNotSaveException(code: 0): The stock item was unable to be saved. Please try again. at /magento_root/vendor/magento/module-catalog-inventory/Model/Stock/StockItemRepository.php:187,
      Magento\Framework\Exception\CouldNotSaveException(code: 0): Could not save Source Item at /magento_root/vendor/magento/module-inventory/Model/SourceItem/Command/Handler/SourceItemsSaveHandler.php:78,
      Zend_Db_Statement_Exception(code: 23000): SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`magento_db`.`inventory_source_item`, CONSTRAINT `INVENTORY_SOURCE_ITEM_SOURCE_CODE_INVENTORY_SOURCE_SOURCE_CODE` FOREIGN KEY (`source_code`) REFERENCES `inventory_source` (`source_code`) ON DEL), query was: INSERT INTO inventory_source_item (`source_code`, `sku`, `quantity`, `status`) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE `quantity` = VALUES(`quantity`), `status` = VALUES(`status`) at /magento_root/vendor/magento/zendframework1/library/Zend/Db/Statement/Pdo.php:235,
      PDOException(code: 23000): SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`magento_db`.`inventory_source_item`, CONSTRAINT `INVENTORY_SOURCE_ITEM_SOURCE_CODE_INVENTORY_SOURCE_SOURCE_CODE` FOREIGN KEY (`source_code`) REFERENCES `inventory_source` (`source_code`) ON DEL) at /magento_root/vendor/magento/zendframework1/library/Zend/Db/Statement/Pdo.php:228)"}


      I am using below code to create product programmatically, injected MagentoCatalogModelProductFactory $productFactory, creating product as below



      $_product = $this->_productFactory->create();

      $mainImage = "";
      $imagesToImport = "";
      if (isset($productData['images'])) {
      $images = explode(',', $productData['images']);
      $mainImage = $images[0];
      array_shift($images);
      if (count($images) > 0) {
      if (count($images) > 1) {
      $imagesToImport = implode(';', $images);
      } else {
      $imagesToImport = $images[0];
      }
      }
      }
      $urlKey = $this->geturlKey($productData['name']);
      $_product->setName($productData['name']);
      $_product->setTypeId('simple');
      $_product->setAttributeSetId(4);
      $_product->setCategoryIds($this->getCategoryId($productData['category']));
      $_product->setSku($productData['sku']);
      $_product->setStatus(2);
      $_product->setUrlKey(strtolower($urlKey) . '-' . $productData['sku']);
      $_product->setWebsiteIds(array(1));
      $_product->setVisibility(4);
      $_product->setDescription($productData['description']);
      $_product->setShortDescription($productData['short_description']);
      $_product->setPrice($productData['price']);
      if (isset($productData['special_price'])) {
      $_product->setSpecialPrice($productData['special_price']);
      $_product->setSpecialFromDate(''); //special price from (MM-DD-YYYY)
      $_product->setSpecialToDate(''); //special price to (MM-DD-YYYY)
      }
      $_product->setMetaTitle($productData['meta_title']);
      $_product->setMetaKeyword($productData['meta_keyword']);
      if (!empty($productData['tier_price'])) {
      $_product->setTierPrices($productData['tier_price']);
      }
      $_product->setWeight($productData['weight']);
      $_product->setMetaDescription($productData['meta_description']);
      $_product->setTaxClassId($productData['tax_class_id']);
      $shoeColorId = $this->_eavAttribute->getIdByCode('catalog_product', 'color');
      $shoeBrandId = $this->_eavAttribute->getIdByCode('catalog_product', 'manufacturer');
      $_product->setColor($this->getAttributeOptionId($productData['color'], $shoeColorId, 'color'));
      $_product->setManufacturer($this->getAttributeOptionId($productData['manufacturer'], $shoeBrandId, 'manufacturer'));
      $_product->setStockData(
      array(
      'use_config_manage_stock' => 0, //'Use config settings' checkbox
      'manage_stock' => 1, //manage stock
      'is_in_stock' => $productData['is_in_stock'], //Stock Availability
      'qty' => $productData['stock'], //qty
      )
      );
      $_product->save();


      The issue with code is missing inventory source details, I am looking for a way to create product programmatically and assigning the source at same time .



      How can I create product programmatically with proper inventory management?







      product magento2.3 magento-enterprise-2 multi-source-inventory






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 30 mins ago









      PiyushPiyush

      4,78872053




      4,78872053






















          0






          active

          oldest

          votes











          Your Answer








          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "479"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f258507%2fassign-inventory-source-while-programmatically-creating-product%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Magento Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f258507%2fassign-inventory-source-while-programmatically-creating-product%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Polycentropodidae

          Magento 2 Error message: Invalid state change requested

          Paulmy