How to add tracking number programmatically for shipments in magento 2.3?
-
14-03-2021 - |
Question
I want to add the tracking numbers only for created shipment. I tried below approach and getting an error.
We cannot create an empty shipment.
How can i add only the tracking number programmatically.
$orderNumber = '000000001';
$order = $this->orderFactory->loadByIncrementId($orderNumber);
if($order->hasInvoices()){
$shipment = $this->orderModel->toShipment($order);
foreach ($order->getAllItems() AS $orderItem) {
if (!$orderItem->getQtyToShip() || $orderItem->getIsVirtual()) {
continue;
}
$qtyShipped = $orderItem->getQtyToShip();
$shipmentItem = $this->orderModel->itemToShipmentItem($orderItem)->setQty($qtyShipped);
$shipment->addItem($shipmentItem);
}
$shipment->register();
$shipment->getOrder()->setIsInProcess(true);
try {
$trackingIds = array(
'0'=>array('carrier_code'=>'fedex','title' => 'Federal Express','number'=>'3131331230'),
'1'=>array('carrier_code'=>'ups','title' => 'UPS Ground','number'=>'1312312')
);
foreach ($trackingIds as $trackingId) {
$data = array(
'carrier_code' => $trackingId['carrier_code'],
'title' => $trackingId['title'],
'number' => $trackingId['number'],
);
$track = $this->trackFactory->create()->addData($data);
$shipment->addTrack($track)->save();
$shipment->addTrack($track);
$this->shipmentRepository->save($shipment);
}
$shipment->save();
$shipment->getOrder()->save();
// Send email
$this->_shipmentNotifier->notify($shipment);
$shipment->save();
enter code here
No correct solution
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange