W3cubDocs

/Drupal 8

function image_entity_presave

image_entity_presave(EntityInterface $entity)

Implements hook_entity_presave().

Transforms default image of image field from array into single value at save.

File

core/modules/image/image.module, line 339
Exposes global functionality for creating image styles.

Code

function image_entity_presave(EntityInterface $entity) {
  // Get the default image settings, return if not saving an image field storage
  // or image field entity.
  $default_image = [];
  if (($entity instanceof FieldStorageConfigInterface || $entity instanceof FieldConfigInterface) && $entity->getType() == 'image') {
    $default_image = $entity->getSetting('default_image');
  }
  else {
    return;
  }

  if ($entity->isSyncing()) {
    return;
  }

  $uuid = $default_image['uuid'];
  if ($uuid) {
    $original_uuid = isset($entity->original) ? $entity->original->getSetting('default_image')['uuid'] : NULL;
    if ($uuid != $original_uuid) {
      $file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid);
      if ($file) {
        $image = \Drupal::service('image.factory')->get($file->getFileUri());
        $default_image['width'] = $image->getWidth();
        $default_image['height'] = $image->getHeight();
      }
      else {
        $default_image['uuid'] = NULL;
      }
    }
  }
  // Both FieldStorageConfigInterface and FieldConfigInterface have a
  // setSetting() method.
  $entity->setSetting('default_image', $default_image);
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!modules!image!image.module/function/image_entity_presave/8.1.x