1 file.field.inc file_field_update($entity_type, $entity, $field, $instance, $langcode, &$items)

Implements hook_field_update().

Checks for files that have been removed from the object.

File

core/modules/file/file.field.inc, line 246
Field module functionality for the File module.

Code

function file_field_update($entity_type, $entity, $field, $instance, $langcode, &$items) {
  $id = $entity->id();

  // 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) {
      if ($file = file_load($item['fid'])) {
        file_usage_add($file, 'file', $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 = $entity->original;
  $original_fids = array();
  if (!empty($original->{$field['field_name']}[$langcode])) {
    foreach ($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.
        if ($file = file_load($original_item['fid'])) {
          file_usage_delete($file, 'file', $entity_type, $id);
        }
      }
    }
  }

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