You are here

function field_collection_update_7008 in Field collection 7

Update fields in field collections already set to use Entity Translation.

File

./field_collection.install, line 365
Install, update and uninstall functions for the field_collection module.

Code

function field_collection_update_7008() {

  // Include FieldCollectionItemEntity class.
  module_load_include('inc', 'field_collection', 'field_collection.entity');
  $results = array();
  foreach (field_info_fields() as $f_name => $field) {
    if ($field['translatable'] == 1 && isset($field['bundles']['field_collection_item'])) {
      $query = new EntityFieldQuery();
      $query
        ->entityCondition('entity_type', 'field_collection_item')
        ->fieldLanguageCondition($f_name, LANGUAGE_NONE);
      $query_result = $query
        ->execute();
      if (isset($query_result['field_collection_item'])) {
        $results += $query_result['field_collection_item'];
      }
    }
  }
  if (count($results)) {
    $orphans = array();
    $ids = array_keys($results);
    $field_collection_items = entity_load('field_collection_item', $ids);
    foreach ($field_collection_items as $item) {

      /** @var FieldCollectionItemEntity $item */
      if ($item
        ->hostEntity()) {
        $item
          ->copyTranslations(LANGUAGE_NONE);
        $item
          ->save(TRUE);
      }
      else {
        $orphans[] = $item
          ->identifier();
      }
    }
    if ($orphans) {
      $count = count($orphans);
      entity_delete_multiple('field_collection_item', $orphans);
      drupal_set_message("Deleted {$count} orphaned field collection items.");
    }
  }
}