You are here

function media_field_update in D7 Media 7

Implements hook_field_update().

Checks for files that have been removed from the object.

File

includes/media.fields.inc, line 408
: Provides a "Multimedia asset" field to the fields API

Code

function media_field_update($entity_type, $entity, $field, $instance, $langcode, &$items) {
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);

  // On new revisions, all files are considered to be a new usage and no
  // deletion of previous file usages are necessary.
  if (!empty($entity->revision)) {
    foreach ($items as $item) {
      $file = (object) $item;
      file_usage_add($file, 'media', $entity_type, $id);
    }
    return;
  }

  // Build a display of the current FIDs.
  $current_fids = array();
  foreach ($items as $item) {
    $current_fids[] = $item['fid'];
  }

  // Compare the original field values with the ones that are being saved.
  $original_fids = array();
  if (!empty($entity->original->{$field['field_name']}[$langcode])) {
    foreach ($entity->original->{$field['field_name']}[$langcode] as $original_item) {
      $original_fids[] = $original_item['fid'];
      if (isset($original_item['fid']) && !in_array($original_item['fid'], $current_fids)) {

        // Decrement the file usage count by 1.
        $file = (object) $original_item;
        file_usage_delete($file, 'media', $entity_type, $id, 1);
      }
    }
  }

  // Add new usage entries for newly added files.
  foreach ($items as $item) {
    if (!in_array($item['fid'], $original_fids)) {
      $file = (object) $item;
      file_usage_add($file, 'media', $entity_type, $id);
    }
  }
}