From 908848f3bdec48c8d80331a62e46c74b6797fd45 Mon Sep 17 00:00:00 2001
From: James Silver <james.silver@computerminds.co.uk>
Date: Mon, 13 Jun 2011 11:21:34 +0100
Subject: [PATCH] Issue #1186826: Delete orphaned field_collection_items when their value is deleted

---
 field_collection.module |   30 ++++++++++++++++++++++++++++++
 1 files changed, 30 insertions(+), 0 deletions(-)

diff --git a/field_collection.module b/field_collection.module
index 00e8d27..3e6d408 100644
--- a/field_collection.module
+++ b/field_collection.module
@@ -511,6 +511,36 @@ function field_collection_field_presave($entity_type, $entity, $field, $instance
 }
 
 /**
+ * Implements hook_field_update().
+ *
+ * Checks for field_collection_item entities that have been removed from the object.
+ */
+function field_collection_field_update($entity_type, $entity, $field, $instance, $langcode, &$items) {
+  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
+
+  // On new revisions, all original field_collection_items may still
+  // be associated with the previous revision, so must be preserved.
+  if (!empty($entity->revision)) {
+    return;
+  }
+
+  // Array of the current field_collection_item entity_ids.
+  $current_ids = field_collection_field_item_to_ids($items);
+
+  // Create a bare-bones entity so that we can load its previous values.
+  $original = entity_create_stub_entity($entity_type, array($id, $vid, $bundle));
+  field_attach_load($entity_type, array($id => $original), FIELD_LOAD_CURRENT, array('field_id' => $field['id']));
+
+  // Compare the original field values with the ones that are being saved.
+  if (!empty($original->{$field['field_name']}[$langcode])) {
+    $original_ids = field_collection_field_item_to_ids($original->{$field['field_name']}[$langcode]);
+    $orphaned_field_collection_items = array_diff($original_ids, $current_ids);
+    // Delete orphaned field_collection_item entities. Otherwise they'll be around forever.
+    entity_delete_multiple('field_collection_item', $orphaned_field_collection_items);
+  }
+}
+
+/**
  * Implements hook_field_delete().
  */
 function field_collection_field_delete($entity_type, $entity, $field, $instance, $langcode, &$items) {
-- 
1.7.1

