You are here

function image_field_caption_entity_update in Image Field Caption 8

Implements hook_entity_update().

1 call to image_field_caption_entity_update()
image_field_caption_entity_insert in ./image_field_caption.module
Implements hook_entity_insert().

File

./image_field_caption.module, line 202
Provides a caption textarea for image fields.

Code

function image_field_caption_entity_update(EntityInterface $entity) {
  $imageCaption = Drupal::service('image_field_caption.storage');

  // For a fieldable entity.
  if ($entity instanceof FieldableEntityInterface) {

    // Get the field names of all image fields.
    $field_names = _image_field_caption_get_image_field_names($entity);
    foreach ($field_names as $field_name) {

      // Get the current field settings.
      $settings = $entity
        ->get($field_name)
        ->getSettings();

      // If the caption is not enabled => pass this field.
      if (empty($settings['caption_field'])) {
        continue;
      }

      // Delete the caption associated to this field.
      $imageCaption
        ->deleteCaption($entity
        ->getEntityTypeId(), $entity
        ->bundle(), $field_name, $entity
        ->id(), $entity
        ->language()
        ->getId());

      // Delete the caption revision associated to this field.

      /*
      $imageCaption->deleteCaptionRevision($entity->getEntityTypeId(), $entity->bundle(), $field_name, $entity->id(), $entity->getRevisionId(), $entity->language()->getId());
      */

      // Get the current field values.
      $values = $entity
        ->get($field_name)
        ->getValue();
      foreach ($values as $delta => $value) {

        // If a caption text is defined.
        if (!empty($value['image_field_caption']['value'])) {

          // Insert the caption associated to this field.
          // @todo Do the insertion using a multiple query instead several queries into a foreach;
          $revision_id = empty($entity
            ->getRevisionId()) ? $entity
            ->id() : $entity
            ->getRevisionId();
          $imageCaption
            ->insertCaption($entity
            ->getEntityTypeId(), $entity
            ->bundle(), $field_name, $entity
            ->id(), $revision_id, $entity
            ->language()
            ->getId(), $delta, $value['image_field_caption']['value'], $value['image_field_caption']['format']);

          // Insert the caption revision associated to this field.

          /*
          if ($entity->isNewRevision()) {
            $imageCaption->insertCaptionRevision(
              $entity->getEntityTypeId(),
              $entity->bundle(),
              $field_name,
              $entity->id(),
              $revision_id,
              $entity->language()->getId(),
              $delta,
              $value['image_field_caption']['value'],
              $value['image_field_caption']['format']
            );
          }
          */
        }
      }
    }
  }
}