2

Quick question I hope someone can easily answer.

There are two order events for order delete listed here: https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/order/src/Event/OrderEvents.php

commerce_order.commerce_order.delete

and

commerce_order.commerce_order_item.delete

I want to delete some related entities when an order line is deleted, so i can hook into commerce_order.commerce_order_item.delete, but my question is if an entire order is deleted will this event also be triggered for each individual line, or do i need to repeat my code also for commerce_order.commerce_order.delete and loop through each line on the order?

1
  • Well... there is one way to find out, are you thinking what I'm thinking?
    – No Sssweat
    Feb 17, 2022 at 12:25

1 Answer 1

2

if an entire order is deleted will this event also be triggered for each individual line

Yes it will - the commerce order entity has a postDelete method which loops through the order items and deletes them one by one

public static function postDelete(EntityStorageInterface $storage, array $entities) {
  parent::postDelete($storage, $entities);

  // Delete the order items of a deleted order.
  $order_items = [];
  /** @var \Drupal\commerce_order\Entity\OrderInterface $entity */
  foreach ($entities as $entity) {
    foreach ($entity->getItems() as $order_item) {
      $order_items[$order_item->id()] = $order_item;
    }
  }
  /** @var \Drupal\commerce_order\OrderItemStorageInterface $order_item_storage */
  $order_item_storage = \Drupal::service('entity_type.manager')->getStorage('commerce_order_item');
  $order_item_storage->delete($order_items);
}

Deleteing the order item will invoke the event you're subscribing to, so no need to do anything else.

2
  • Perfect, thank you very much. Feb 17, 2022 at 18:27
  • I got this all working but I have another problem, I did not relaise that commerce_order.commerce_order_item.delete is fired not just when an order line is deleted, but also when an item is simply removed from the cart. Is there any distinction between deleting a line from a completed order and removing an item from the cart, in terms of a subscribed event? is there another event I should use instead? Feb 24, 2022 at 16:31

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.