function ImageHooks::fieldConfigUpdate

Implements hook_ENTITY_TYPE_update() for 'field_config'.

Attributes

#[Hook('field_config_update')]

File

core/modules/image/src/Hook/ImageHooks.php, line 320

Class

ImageHooks
Hook implementations for image.

Namespace

Drupal\image\Hook

Code

public function fieldConfigUpdate(FieldConfigInterface $field) : void {
  $field_storage = $field->getFieldStorageDefinition();
  if ($field_storage->getType() != 'image') {
    // Only act on image fields.
    return;
  }
  $prior_instance = $field->getOriginal();
  $uuid_new = $field->getSetting('default_image')['uuid'];
  $uuid_old = $prior_instance->getSetting('default_image')['uuid'];
  // If the old and new files do not match, update the default accordingly.
  $file_new = $uuid_new ? \Drupal::service('entity.repository')->loadEntityByUuid('file', $uuid_new) : FALSE;
  if ($uuid_new != $uuid_old) {
    // Save the new file, if present.
    if ($file_new) {
      $file_new->setPermanent();
      $file_new->save();
      \Drupal::service('file.usage')->add($file_new, 'image', 'default_image', $field->uuid());
    }
    // Delete the old file, if present.
    if ($uuid_old && ($file_old = \Drupal::service('entity.repository')->loadEntityByUuid('file', $uuid_old))) {
      \Drupal::service('file.usage')->delete($file_old, 'image', 'default_image', $field->uuid());
    }
  }
  // If the upload destination changed, then move the file.
  if ($file_new && StreamWrapperManager::getScheme($file_new->getFileUri()) != $field_storage->getSetting('uri_scheme')) {
    $directory = $field_storage->getSetting('uri_scheme') . '://default_images/';
    \Drupal::service('file_system')->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY);
    \Drupal::service('file.repository')->move($file_new, $directory . $file_new->getFilename());
  }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.