Score:1

Commerce order delete and order item delete events

cn flag

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?

No Sssweat avatar
ua flag
Well... there is one way to find out, are you thinking what I'm thinking?
Score:2
cn flag

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.

thiokol avatar
cn flag
Perfect, thank you very much.
thiokol avatar
cn flag
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?
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.