3

Which hook is invoked when an order is updated?

I created a module that must perform some operations when an order is modified, for example when its status is changed or when an item is changed.

3 Answers 3

4

Commerce doesn't provide an explicit hook for that (these are the hooks it does define for orders).

Since a commerce order is an entity, you're looking for hook_entity_update(), which is used to

Act on entities when inserted.

1
  • 1
    thanks. I am working on it. My issue is do some operations when an entity with type "commerce_order" is updated. so I used "hook_entity_update" and in my function I used this condition if($type == 'commerce_order') {}
    – Mehrdad201
    Commented Nov 8, 2013 at 17:18
7

The documentation for commerce_order_status_update() says:

While there is no explicit Rules event or hook devoted to an order status being updated...

It is possible to use hook_commerce_order_presave():

/**
 * Implements hook_commerce_order_presave().
 */
function my_module_commerce_order_presave($order) {
  if ($order->status != $order->original->status) {
    drupal_set_message("The order status changed from {$order->original->status} to {$order->status}");
  }
}

Here's an optional helper function for use elsewhere if you have an $order object, and are curious if its status has changed from what is stored in the database:

/**
 * Given an order object, this returns FALSE if the order status has not
 * changed. If it has changed, it returns an associative array with the
 * following keys: new_order_status, old_order_status
 */
function my_module_order_status_changed($order) {
  $result['new_order_status'] = $order->status;
  $result['old_order_status'] = db_select('commerce_order', 'co')
    ->fields('co', array('status'))
    ->condition('co.order_id', $order->order_id)
    ->execute()
    ->fetchField();
  if ($result['new_order_status'] == $result['old_order_status']) {
    return FALSE;
  }
  return $result;
}
2
  • Where did you pull out hook_order_status_changed. Doesnt work and I dont see anywhere hook_order_status_changed documented?
    – Blissful
    Commented Sep 24, 2015 at 0:43
  • 3
    The hook is hook_commerce_order_presave() with the boolean outlined above. There is no hook called hook_order_status_changed(), that is just a helper function I've created. Commented Sep 24, 2015 at 16:19
1

Try: hook_commerce_order_presave($order);

It allows you to prepare order data before it is saved.

1
  • can you provide some example code? Commented Nov 8, 2013 at 16:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.