You are here

protected function AvatarKitEntityFieldHandler::pushFileIntoEntity in Avatar Kit 8.2

Places a reference to a file in the field of a given entity.

Parameters

\Drupal\Core\Entity\FieldableEntityInterface $entity: The destination entity.

string $field_name: Name of a file field.

\Drupal\file\FileInterface $file: The new file.

1 call to AvatarKitEntityFieldHandler::pushFileIntoEntity()
AvatarKitEntityFieldHandler::copyCacheToEntity in src/AvatarKitEntityFieldHandler.php
Copies the avatar in a cache entity to an entity.

File

src/AvatarKitEntityFieldHandler.php, line 74

Class

AvatarKitEntityFieldHandler
Handles pushing avatar caches into entities.

Namespace

Drupal\avatars

Code

protected function pushFileIntoEntity(FieldableEntityInterface $entity, string $field_name, FileInterface $file) {

  /** @var \Drupal\Core\Field\EntityReferenceFieldItemList $field_item_list */
  $field_item_list = $entity
    ->get($field_name);

  // Determine if file is already in the entity.
  $files = $field_item_list
    ->referencedEntities();
  $current_file = reset($files);
  if ($current_file instanceof FileInterface && $current_file
    ->id() == $file
    ->id()) {
    return;
  }

  // Replace existing values, if any, with new file.
  $field_item_list
    ->setValue([
    $file,
  ]);
  $entity
    ->save();
}