Emil Vikström
Emil Vikström

Reputation: 91942

Get tracking ID from shipment track event in Magento

I am trying to get the tracking number from the sales_order_shipment_track_save_after event in Magento 1.9.0.1. For some reason the event does not seem to include the shipment, because $observer->getEvent()->getShipment() returns NULL. Am I using the wrong event?

These are the relevant parts of my code:

config.xml (module)

<events>
  <sales_order_shipment_track_save_after>
    <observers>
      <pixelstore_sms>
        <type>model</type>
        <class>pixelstore_sms/observer</class>
        <method>shipments</method>
      </pixelstore_sms>
    </observers>
  </sales_order_shipment_track_save_after>
</events>

Observer.php (model)

public function shipments($observer) {
    $event = $observer->getEvent();
    $shipment = $event->getShipment();
    if (!$shipment) {
        Mage::log('shipments event did not contain shipment', null, 'track.log');
        return false;
    }
    // We never reach this far
    $trackings = $shipment->getAllTracks();
    $tracking = end($trackings);
    $trackingId = $tracking->getNumber();
    // Here I would prefer to have the tracking ID in $trackingId
}

As you might have guessed, the if statement matches. get_class() shows that the observer is Varien_Event_Observer.

Am I observing the wrong event, or is there some other method I should call to get the tracking ID?

Upvotes: 5

Views: 3284

Answers (2)

Emil Vikstr&#246;m
Emil Vikstr&#246;m

Reputation: 91942

I found out that the event contains the Mage_Sales_Model_Order_Shipment_Track object under the key track. This means I could get it from the event with $event->getData('track'), $event['track'] or just $event->getTrack(). So this is what finally solved my problem:

public function shipments(Varien_Event_Observer $observer) {
  $event = $observer->getEvent();
  $track = $event->getTrack();
  $trackingId = $track->getNumber();

  // The shipment itself can be found in the track object,
  // and the order inside the shipment object:
  $shipment = $track->getShipment();
  $order = $shipment->getOrder();
}

It was all a misunderstanding about what was included in the actual event.

Upvotes: 2

cleong
cleong

Reputation: 220

It should be able to retrieve the order object even as the base observer.

public function shipments(Varien_Event_Observer $observer) {
$event = $observer->getEvent();
$shipment = $event->getShipment();
if (!$shipment) {
Mage::log('shipments event did not contain shipment', null, 'track.log');
return false;
}
// We never reach this far
$trackingId = $observer->getOrder()->getTrackingNumbers();
// Here I would prefer to have the tracking ID in $trackingId
}

Upvotes: 0

Related Questions