You are here

function commerce_line_item_delete_references in Commerce Core 7

Deletes any references to the given line item.

File

modules/line_item/commerce_line_item.module, line 665
Defines the core Commerce line item entity and API functions interact with line items on orders.

Code

function commerce_line_item_delete_references($line_item) {

  // Check the data in every line item reference field.
  foreach (commerce_info_fields('commerce_line_item_reference') as $field_name => $field) {

    // Query for any entity referencing the deleted line item in this field.
    $query = new EntityFieldQuery();
    $query
      ->fieldCondition($field_name, 'line_item_id', $line_item->line_item_id, '=');
    $result = $query
      ->execute();

    // If results were returned...
    if (!empty($result)) {

      // Loop over results for each type of entity returned.
      foreach ($result as $entity_type => $data) {

        // Load the entities of the current type.
        $entities = entity_load($entity_type, array_keys($data));

        // Loop over each entity and remove the reference to the deleted line item.
        foreach ($entities as $entity_id => $entity) {
          commerce_entity_reference_delete($entity, $field_name, 'line_item_id', $line_item->line_item_id);
          entity_save($entity_type, $entity);
        }
      }
    }
  }
}