Adding tracking number to existing orders from CSV file Programmatically in Magento 2How do I add tracking number to current order shipment in Magento 2?Adding a barcode for Order number and Tracking Number in Shipment PDFProgrammatically create new orders from multiple existing ordersSend tracking number programmatically with SOAPCatch errors from validation when saving product or category ($product->validate() or $category->validate())Magento 2 Log Bundle Product Data in List Page?How do I add tracking number to current order shipment in Magento 2?Magento 2 - How to create item wise shipment And add tracking number programmaticallyFetching last tracking number from another magento usin APIAdding a tracking number and shipping label to shipmentImport a csv file in Bo magento 2

Etiquette around loan refinance - decision is going to cost first broker a lot of money

Were any external disk drives stacked vertically?

Infinite Abelian subgroup of infinite non Abelian group example

Western buddy movie with a supernatural twist where a woman turns into an eagle at the end

Why are electrically insulating heatsinks so rare? Is it just cost?

What exploit are these user agents trying to use?

A reference to a well-known characterization of scattered compact spaces

In Romance of the Three Kingdoms why do people still use bamboo sticks when papers are already invented?

1960's book about a plague that kills all white people

What killed these X2 caps?

What mechanic is there to disable a threat instead of killing it?

How could indestructible materials be used in power generation?

Doing something right before you need it - expression for this?

Should I tell management that I intend to leave due to bad software development practices?

How badly should I try to prevent a user from XSSing themselves?

Anagram holiday

Is there a hemisphere-neutral way of specifying a season?

Can I use a neutral wire from another outlet to repair a broken neutral?

Today is the Center

Blender 2.8 I can't see vertices, edges or faces in edit mode

Why "Having chlorophyll without photosynthesis is actually very dangerous" and "like living with a bomb"?

Why is it a bad idea to hire a hitman to eliminate most corrupt politicians?

Neighboring nodes in the network

Why do I get two different answers for this counting problem?



Adding tracking number to existing orders from CSV file Programmatically in Magento 2


How do I add tracking number to current order shipment in Magento 2?Adding a barcode for Order number and Tracking Number in Shipment PDFProgrammatically create new orders from multiple existing ordersSend tracking number programmatically with SOAPCatch errors from validation when saving product or category ($product->validate() or $category->validate())Magento 2 Log Bundle Product Data in List Page?How do I add tracking number to current order shipment in Magento 2?Magento 2 - How to create item wise shipment And add tracking number programmaticallyFetching last tracking number from another magento usin APIAdding a tracking number and shipping label to shipmentImport a csv file in Bo magento 2






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I have a csv file with 3 columns ( Order#|Carrier|Tracking), how do i add the tracking numbers programmatically by reading the csv file through a script?



there are some reference here, but i'm not exactly sure how to put it together ( how to declare trackfactory, shipment etc)
How do I add tracking number to current order shipment in Magento 2?



$data = array(
'carrier_code' => 'ups',
'title' => 'United Parcel Service',
'number' => 'TORD23254WERZXd3', // Replace with your tracking number
);

$track = $this->trackFactory->create()->addData($data);
$shipment->addTrack($track)->save();


below is the script i use to update quantity programmatically through reading an csv file for reference:



<?php $file = fopen('pub/media/files/inventory.csv', 'r', '"'); // set path to the CSV file
if ($file !== false)

require __DIR__ . '/app/bootstrap.php';
$bootstrap = MagentoFrameworkAppBootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('MagentoFrameworkAppState');
$state->setAreaCode('adminhtml');

// used for updating product info
$productRepository = $objectManager->get('MagentoCatalogModelProductRepository');

// used for updating product stock
$stockRegistry = $objectManager->get('MagentoCatalogInventoryApiStockRegistryInterface');

// add logging capability
$writer = new ZendLogWriterStream(BP . '/var/log/import-update.log');
$logger = new ZendLogLogger();
$logger->addWriter($writer);

// enter the number of data fields you require the product row inside the CSV file to contain
$required_data_fields = 2; //change for 3 to 2

$header = fgetcsv($file); // get data headers and skip 1st row

while ( $row = fgetcsv($file, 5000, ",") )

$data_count = count($row);
if ($data_count < 1)
continue;


$data = array();
$data = array_combine($header, $row);

$sku = $data['sku'];
if ($data_count < $required_data_fields)
$logger->info("Skipping product sku " . $sku . ". Not enough data to import.");
continue;


$qty = trim($data['qty']);
//$price = trim($data['price']);

echo 'Updating product SKU: '.$sku.', with Qty: '.$qty.'<br />n'; // .' and Price:'.$price.'<br />';
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////updating price/////////////////////////////////////////////////////////////////////
//try
// $product = $productRepository->get($sku);
//
//catch (Exception $e)
// $logger->info("Invalid product SKU: ".$sku);
// continue;
//
//
// You can set other product data with $product->setAttributeName() if you want to update more data
//if ($product->getPrice() != $price)
// $product->setPrice($price)
// ->setStoreId(0) // this is needed because if you have multiple store views, each individual store view will get "Use default value" unchecked for multiple attributes - which causes issues.
// ->save();
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////updating quantity/////////////////////////////////////////////////////////////////////
try
$stockItem = $stockRegistry->getStockItemBySku($sku);

catch (Exception $e)
$logger->info("Invalid stock for product SKU: ".$sku);
continue;


if ($stockItem->getQty() != $qty)
$stockItem->setQty($qty);
if ($qty > 0)
$stockItem->setIsInStock(1);

if ($qty < 1)
$stockItem->setIsInStock(0); //clean up first time

$stockRegistry->updateStockItemBySku($sku, $stockItem);


fclose($file);

?>









share|improve this question




























    0















    I have a csv file with 3 columns ( Order#|Carrier|Tracking), how do i add the tracking numbers programmatically by reading the csv file through a script?



    there are some reference here, but i'm not exactly sure how to put it together ( how to declare trackfactory, shipment etc)
    How do I add tracking number to current order shipment in Magento 2?



    $data = array(
    'carrier_code' => 'ups',
    'title' => 'United Parcel Service',
    'number' => 'TORD23254WERZXd3', // Replace with your tracking number
    );

    $track = $this->trackFactory->create()->addData($data);
    $shipment->addTrack($track)->save();


    below is the script i use to update quantity programmatically through reading an csv file for reference:



    <?php $file = fopen('pub/media/files/inventory.csv', 'r', '"'); // set path to the CSV file
    if ($file !== false)

    require __DIR__ . '/app/bootstrap.php';
    $bootstrap = MagentoFrameworkAppBootstrap::create(BP, $_SERVER);

    $objectManager = $bootstrap->getObjectManager();

    $state = $objectManager->get('MagentoFrameworkAppState');
    $state->setAreaCode('adminhtml');

    // used for updating product info
    $productRepository = $objectManager->get('MagentoCatalogModelProductRepository');

    // used for updating product stock
    $stockRegistry = $objectManager->get('MagentoCatalogInventoryApiStockRegistryInterface');

    // add logging capability
    $writer = new ZendLogWriterStream(BP . '/var/log/import-update.log');
    $logger = new ZendLogLogger();
    $logger->addWriter($writer);

    // enter the number of data fields you require the product row inside the CSV file to contain
    $required_data_fields = 2; //change for 3 to 2

    $header = fgetcsv($file); // get data headers and skip 1st row

    while ( $row = fgetcsv($file, 5000, ",") )

    $data_count = count($row);
    if ($data_count < 1)
    continue;


    $data = array();
    $data = array_combine($header, $row);

    $sku = $data['sku'];
    if ($data_count < $required_data_fields)
    $logger->info("Skipping product sku " . $sku . ". Not enough data to import.");
    continue;


    $qty = trim($data['qty']);
    //$price = trim($data['price']);

    echo 'Updating product SKU: '.$sku.', with Qty: '.$qty.'<br />n'; // .' and Price:'.$price.'<br />';
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////updating price/////////////////////////////////////////////////////////////////////
    //try
    // $product = $productRepository->get($sku);
    //
    //catch (Exception $e)
    // $logger->info("Invalid product SKU: ".$sku);
    // continue;
    //
    //
    // You can set other product data with $product->setAttributeName() if you want to update more data
    //if ($product->getPrice() != $price)
    // $product->setPrice($price)
    // ->setStoreId(0) // this is needed because if you have multiple store views, each individual store view will get "Use default value" unchecked for multiple attributes - which causes issues.
    // ->save();
    //
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////updating quantity/////////////////////////////////////////////////////////////////////
    try
    $stockItem = $stockRegistry->getStockItemBySku($sku);

    catch (Exception $e)
    $logger->info("Invalid stock for product SKU: ".$sku);
    continue;


    if ($stockItem->getQty() != $qty)
    $stockItem->setQty($qty);
    if ($qty > 0)
    $stockItem->setIsInStock(1);

    if ($qty < 1)
    $stockItem->setIsInStock(0); //clean up first time

    $stockRegistry->updateStockItemBySku($sku, $stockItem);


    fclose($file);

    ?>









    share|improve this question
























      0












      0








      0








      I have a csv file with 3 columns ( Order#|Carrier|Tracking), how do i add the tracking numbers programmatically by reading the csv file through a script?



      there are some reference here, but i'm not exactly sure how to put it together ( how to declare trackfactory, shipment etc)
      How do I add tracking number to current order shipment in Magento 2?



      $data = array(
      'carrier_code' => 'ups',
      'title' => 'United Parcel Service',
      'number' => 'TORD23254WERZXd3', // Replace with your tracking number
      );

      $track = $this->trackFactory->create()->addData($data);
      $shipment->addTrack($track)->save();


      below is the script i use to update quantity programmatically through reading an csv file for reference:



      <?php $file = fopen('pub/media/files/inventory.csv', 'r', '"'); // set path to the CSV file
      if ($file !== false)

      require __DIR__ . '/app/bootstrap.php';
      $bootstrap = MagentoFrameworkAppBootstrap::create(BP, $_SERVER);

      $objectManager = $bootstrap->getObjectManager();

      $state = $objectManager->get('MagentoFrameworkAppState');
      $state->setAreaCode('adminhtml');

      // used for updating product info
      $productRepository = $objectManager->get('MagentoCatalogModelProductRepository');

      // used for updating product stock
      $stockRegistry = $objectManager->get('MagentoCatalogInventoryApiStockRegistryInterface');

      // add logging capability
      $writer = new ZendLogWriterStream(BP . '/var/log/import-update.log');
      $logger = new ZendLogLogger();
      $logger->addWriter($writer);

      // enter the number of data fields you require the product row inside the CSV file to contain
      $required_data_fields = 2; //change for 3 to 2

      $header = fgetcsv($file); // get data headers and skip 1st row

      while ( $row = fgetcsv($file, 5000, ",") )

      $data_count = count($row);
      if ($data_count < 1)
      continue;


      $data = array();
      $data = array_combine($header, $row);

      $sku = $data['sku'];
      if ($data_count < $required_data_fields)
      $logger->info("Skipping product sku " . $sku . ". Not enough data to import.");
      continue;


      $qty = trim($data['qty']);
      //$price = trim($data['price']);

      echo 'Updating product SKU: '.$sku.', with Qty: '.$qty.'<br />n'; // .' and Price:'.$price.'<br />';
      /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////updating price/////////////////////////////////////////////////////////////////////
      //try
      // $product = $productRepository->get($sku);
      //
      //catch (Exception $e)
      // $logger->info("Invalid product SKU: ".$sku);
      // continue;
      //
      //
      // You can set other product data with $product->setAttributeName() if you want to update more data
      //if ($product->getPrice() != $price)
      // $product->setPrice($price)
      // ->setStoreId(0) // this is needed because if you have multiple store views, each individual store view will get "Use default value" unchecked for multiple attributes - which causes issues.
      // ->save();
      //
      /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////updating quantity/////////////////////////////////////////////////////////////////////
      try
      $stockItem = $stockRegistry->getStockItemBySku($sku);

      catch (Exception $e)
      $logger->info("Invalid stock for product SKU: ".$sku);
      continue;


      if ($stockItem->getQty() != $qty)
      $stockItem->setQty($qty);
      if ($qty > 0)
      $stockItem->setIsInStock(1);

      if ($qty < 1)
      $stockItem->setIsInStock(0); //clean up first time

      $stockRegistry->updateStockItemBySku($sku, $stockItem);


      fclose($file);

      ?>









      share|improve this question














      I have a csv file with 3 columns ( Order#|Carrier|Tracking), how do i add the tracking numbers programmatically by reading the csv file through a script?



      there are some reference here, but i'm not exactly sure how to put it together ( how to declare trackfactory, shipment etc)
      How do I add tracking number to current order shipment in Magento 2?



      $data = array(
      'carrier_code' => 'ups',
      'title' => 'United Parcel Service',
      'number' => 'TORD23254WERZXd3', // Replace with your tracking number
      );

      $track = $this->trackFactory->create()->addData($data);
      $shipment->addTrack($track)->save();


      below is the script i use to update quantity programmatically through reading an csv file for reference:



      <?php $file = fopen('pub/media/files/inventory.csv', 'r', '"'); // set path to the CSV file
      if ($file !== false)

      require __DIR__ . '/app/bootstrap.php';
      $bootstrap = MagentoFrameworkAppBootstrap::create(BP, $_SERVER);

      $objectManager = $bootstrap->getObjectManager();

      $state = $objectManager->get('MagentoFrameworkAppState');
      $state->setAreaCode('adminhtml');

      // used for updating product info
      $productRepository = $objectManager->get('MagentoCatalogModelProductRepository');

      // used for updating product stock
      $stockRegistry = $objectManager->get('MagentoCatalogInventoryApiStockRegistryInterface');

      // add logging capability
      $writer = new ZendLogWriterStream(BP . '/var/log/import-update.log');
      $logger = new ZendLogLogger();
      $logger->addWriter($writer);

      // enter the number of data fields you require the product row inside the CSV file to contain
      $required_data_fields = 2; //change for 3 to 2

      $header = fgetcsv($file); // get data headers and skip 1st row

      while ( $row = fgetcsv($file, 5000, ",") )

      $data_count = count($row);
      if ($data_count < 1)
      continue;


      $data = array();
      $data = array_combine($header, $row);

      $sku = $data['sku'];
      if ($data_count < $required_data_fields)
      $logger->info("Skipping product sku " . $sku . ". Not enough data to import.");
      continue;


      $qty = trim($data['qty']);
      //$price = trim($data['price']);

      echo 'Updating product SKU: '.$sku.', with Qty: '.$qty.'<br />n'; // .' and Price:'.$price.'<br />';
      /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////updating price/////////////////////////////////////////////////////////////////////
      //try
      // $product = $productRepository->get($sku);
      //
      //catch (Exception $e)
      // $logger->info("Invalid product SKU: ".$sku);
      // continue;
      //
      //
      // You can set other product data with $product->setAttributeName() if you want to update more data
      //if ($product->getPrice() != $price)
      // $product->setPrice($price)
      // ->setStoreId(0) // this is needed because if you have multiple store views, each individual store view will get "Use default value" unchecked for multiple attributes - which causes issues.
      // ->save();
      //
      /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////updating quantity/////////////////////////////////////////////////////////////////////
      try
      $stockItem = $stockRegistry->getStockItemBySku($sku);

      catch (Exception $e)
      $logger->info("Invalid stock for product SKU: ".$sku);
      continue;


      if ($stockItem->getQty() != $qty)
      $stockItem->setQty($qty);
      if ($qty > 0)
      $stockItem->setIsInStock(1);

      if ($qty < 1)
      $stockItem->setIsInStock(0); //clean up first time

      $stockRegistry->updateStockItemBySku($sku, $stockItem);


      fclose($file);

      ?>






      magento2 shipping programmatically dependency-injection shipment-tracking






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 5 hours ago









      Kris WenKris Wen

      1268




      1268




















          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%2f268844%2fadding-tracking-number-to-existing-orders-from-csv-file-programmatically-in-mage%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%2f268844%2fadding-tracking-number-to-existing-orders-from-csv-file-programmatically-in-mage%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

          Can not update quote_id field of “quote_item” table magento 2Magento 2.1 - We can't remove the item. (Shopping Cart doesnt allow us to remove items before becomes empty)Add value for custom quote item attribute using REST apiREST API endpoint v1/carts/cartId/items always returns error messageCorrect way to save entries to databaseHow to remove all associated quote objects of a customer completelyMagento 2 - Save value from custom input field to quote_itemGet quote_item data using quote id and product id filter in Magento 2How to set additional data to quote_item table from controller in Magento 2?What is the purpose of additional_data column in quote_item table in magento2Set Custom Price to Quote item magento2 from controller

          Magento 2 disable Secret Key on URL's from terminal The Next CEO of Stack OverflowMagento 2 Shortcut/GUI tool to perform commandline tasks for windowsIn menu add configuration linkMagento oAuth : Generating access token and access secretMagento 2 security key issue in Third-Party API redirect URIPublic actions in admin controllersHow to Disable Cache in Custom WidgetURL Key not changing in Magento 2Product URL Key gets deleted when importing custom options - Magento 2Problem with reindex terminalMagento 2 - bin/magento Commands not working in Cpanel Terminal

          Aasi (pallopeli) Navigointivalikko