Skip to content

AutoShipment observer process overrides earlier saved order instance #59

@vinodsowdagar

Description

@vinodsowdagar

The DHLParcel\Shipping\Observer\Autoshipment class is subscribed to the 'sales_order_save_after' event.

The event is dispatched in \Magento\Framework\Model\ResourceModel\Db\AbstractDb::save after the save action has been executed. The save operation happens using a database transaction and this event does not wait for the transaction to be committed.

Normally this wouldn't be a problem, because the afterSave() function in Magento\Framework\Model\AbstractModel updates its own stored data. So whenever you will use the order instance retrieved from the observer object itself, it will have the correct values that were actually supposed to be saved. You can see how that works here: https://github.com/magento/magento2/blob/cd08acf3e9f8ed73cb23a807e9960055c465c477/lib/internal/Magento/Framework/Model/AbstractModel.php#L837-L849

However, you are getting a fresh instance from the database through the OrderRepository and this instance doesn't have all the data yet that the one from the observer has: https://github.com/dhlparcel/plugin-magento2-release/blob/master/Observer/AutoShipment.php#L79

On line 96 you are saving the order yourself, but that is an older instance of the order without all the data which was passed through the 'sales_order_save_after' event. This eventually results in the AutoShipment observer overriding certain values: https://github.com/dhlparcel/plugin-magento2-release/blob/master/Observer/AutoShipment.php#L96

You can see this example happening if you try to get the order, change the state and status and then try to save it through the OrderRepository. When debugging your AutoShipment observer, we can clearly see it happening.

The observer order has the correct values (status and state processing):
image

But the one retrieved through the OrderRepository has not (status and state pending_payment):
image

I think this can maybe be fixed by either using the 'sales_order_save_commit_after' event, because that one actually seems to be implemented with a callback. More information about the differences of both of these events can be found in this article:
https://techflarestudio.com/what-is-the-difference-betweent-save_after-and-save_commit_after-events-magento-2/

Maybe another solution could also be to use a plugin after class instead of an event, but I haven't tested this.

If there are any questions, let me know.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions