You are here

function commerce_product_reference_commerce_product_delete in Commerce Core 7

Implements hook_commerce_product_delete().

Remove references to this product in all product reference field contents.

File

modules/product_reference/commerce_product_reference.module, line 285
Defines a field type for referencing products from other entities.

Code

function commerce_product_reference_commerce_product_delete($product) {

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

    // Query for any entity referencing the deleted product in this field.
    $query = new EntityFieldQuery();
    $query
      ->fieldCondition($field_name, 'product_id', $product->product_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 product.
        foreach ($entities as $entity_id => $entity) {
          commerce_entity_reference_delete($entity, $field_name, 'product_id', $product->product_id);

          // Store the changes to the entity.
          entity_save($entity_type, $entity);
        }
      }
    }
  }
}