diff --git a/field_collection.install b/field_collection.install index 91edfbb..c310bd6 100644 --- a/field_collection.install +++ b/field_collection.install @@ -281,3 +281,79 @@ function field_collection_update_7004() { } } } + +/** + * Copy field_collection_items that are used by multiple entities. + **/ +function field_collection_update_7005() { + // 1. Find all fields of type field_collection. + // 2. Find all items that are used by multiple host-entities + // 3. Make copies of the items: + // a) host entities pointing to the newest revision can keep them. (assume that no revision is reused) + // b) if the specific revision doesn't exit anymore copy the current revision instead + $result = db_query('SELECT field_name FROM field_config WHERE type=:type', array(':type' => 'field_collection')); + foreach ($result as $row) { + $name = $row->field_name; + + $sql = <<item_id))) { + watchdog('field_collection', 'Unable to find field_collection_item with item_id=!item_id', array('!item_id' => $fcid->item_id), WATCHDOG_ERROR); + continue; + } + + $sql = << $fcid->item_id)) as $item) { + $host_entity = entity_load($item->entity_type, array($item->entity_id)); + if (!isset($host_entity[$item->entity_id])) { + // host entity doesn't exist - never mind. + continue; + } else { + $host_entity = $host_entity[$item->entity_id]; + } + + if ($item->revision_id == $current_fc->revision_id) { + // host entities holding the newest revision can keep them. + continue; + } + + if (!($fc = field_collection_item_revision_load($item->revision_id))) { + // The revision stored in the field-item is not available anymore. + // Use the current revision instead. + $fc = clone $current_fc; + $msg = 'Unable to load revision !revision_id - copying the newest. Data might have been lost.'; + watchdog('field_collection', $msg, array('!revision_id' => $item->revision_id), WATCHDOG_WARNING); + } + $fc->is_new = TRUE; + $fc->item_id = NULL; + $fc->revision_id = NULL; + $fc->setHostEntity($item->entity_type, $host_entity, LANGUAGE_NONE, FALSE); + + $host_entity->{$name}[LANGUAGE_NONE][$item->delta] = array( + 'value' => $fc->item_id, + 'revision_id' => $fc->revision_id, + 'entity' => $fc, + ); + entity_save($item->entity_type, $host_entity); + $msg = 'Copied item(item_id=!item_id, revision_id=!revision_id) to new item(item_id=!new_item_id, revision_id=!new_revision_id) for entity !entity_type/!entity_id.'; + $data = array( + '!item_id' => $fcid->item_id, + '!revision_id' => $item->revision_id, + '!new_item_id' => $fc->item_id, + '!new_revision_id' => $fc->revision_id, + '!entity_type' => $item->entity_type, + '!entity_id' => $item->entity_id + ); + watchdog('field_collection', $msg, $data, WATCHDOG_INFO); + } + } + } +}