简体   繁体   中英

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?

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM