Magento – Magento event to observe shipment creation, not invoice

event-observerextensionsshipment

I'm trying to send a text message right after shipment was created in admin panel. I'm observing sales_order_shipment_save_after which works fine. The problem is this event fires on invoice creation too.

I couldn't find the right event for observing only shipment creation. Any suggestion?

I'm on 1.9.2.1.

[EDIT]

I listed all events by adding Mage::log in dispatchEvent method in app/Mage.php. These are the ones which seem related (and I didn't try them already):

sales_order_shipment_save_commit_after
controller_action_postdispatch_adminhtml_sales_order_shipment_save
core_copy_fieldset_sales_convert_order_to_shipment

Which one should I use?

Best Answer

With sales_order_shipment_save_commit_after you will run into the same issue. The other mentioned events do not tell if the shipment was/will be created successfully.

Probably the sales_order_shipment_save_after event is just fine, but you miss a point: The save() method is not only called on create operations but also on update. In your case, I guess, the latter fires on invoice creation.

Stick with the event and test in your observer method whether the shipment was just created or not:

// Observer::shipmentSaveAfter()
if ($observer->getShipment()->getOrigData('entity_id')) {
    // shipment updated, do nothing
    return;
}

// shipment new, send text message

This is not 100% reliable though as the original data is populated on load and as such not necessarily during multiple calls to the save() method.

Alternatively you could register a flag on sales_order_shipment_save_before:

// Observer::shipmentSaveBefore()
if ($observer->getShipment()->isObjectNew()) {
    Mage::register('send_shipment_message', true);
}


// Observer::shipmentSaveAfter()
if (!Mage::registry('send_shipment_message')) {
    // shipment updated, do nothing
    return;
}

Mage::unregister('send_shipment_message');
// shipment new, send text message
Related Topic