How do I add tracking number to current order shipment in Magento 2?
-
05-10-2020 - |
Question
I did find sample codes for Magento 1.x. But I have no idea how to do this on Magento 2.
Can anyone describe how to implement this using Dependency Injection (DI)?
Thanks.
$trackingDetail = array(
'carrier_code' => 'ups',
'title' => 'United Parcel Service',
'number' => 'TORD23254WERZXd3', // Replace with your tracking number
);
$track = Mage::getModel('sales/order_shipment_track')->addData($trackingDetail);
$shipment->addTrack($track);
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($shipment)
->addObject($shipment->getOrder())
->save();
Solution
AFAIK the track object is the same in M2.
However, the rest of the code has changed.
$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();
Where $this->trackFactory
an instance of Magento\Sales\Model\Order\Shipment\TrackFactory
and $shipment
is your shipment object.
OTHER TIPS
Adding to the accepted answer, it would be a good idea to use repositories instead of the deprecated save method. Also added the customer notification after the tracking creation.
/** @var Magento\Sales\Model\Order\ShipmentRepository */
protected $_shipmentRepository;
/** @var Magento\Shipping\Model\ShipmentNotifier */
protected $_shipmentNotifier;
/** @var Magento\Sales\Model\Order\Shipment\TrackFactory */
protected $_trackFactory; //missing ;
public function __construct(
\Magento\Shipping\Model\ShipmentNotifier $shipmentNotifier,
\Magento\Sales\Model\Order\ShipmentRepository $shipmentRepository,
\Magento\Sales\Model\Order\Shipment\TrackFactory $trackFactory)
{
$this->_shipmentNotifier = $shipmentNotifier;
$this->_shipmentRepository = $shipmentRepository;
$this->_trackFactory = $trackFactory;
}
public function addTrack($shipment, $carrierCode, $description, $trackingNumber)
{
/** Creating Tracking */
/** @var Track $track */
$track = $this->_trackFactory->create();
$track->setCarrierCode($carrierCode);
$track->setDescription($description);
$track->setTrackNumber($trackingNumber);
$shipment->addTrack($track);
$this->_shipmentRepository->save($shipment);
/* Notify the customer*/
$this->_shipmentNotifier->notify($shipment);
}
Where $shipment is your shipment object. Notify will notify (send email) to the user and add a history item to the order status history collection.