Skip to content

Instantly share code, notes, and snippets.

@jmolivas
Last active November 1, 2019 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmolivas/1c5d512a7b9be80fa826cf5bb6265fda to your computer and use it in GitHub Desktop.
Save jmolivas/1c5d512a7b9be80fa826cf5bb6265fda to your computer and use it in GitHub Desktop.
Convert entity files as media using Drupal 8

Convert entity files as media using Drupal 8

  • Install Drupal Console

  • Copy content of add-file-image-as-media-image.php to console/snippet/

  • Execute drupal console snippet command

drupal snippet --file=console/snippet/add-file-image-as-media-image.php
<?php
$fileStorage = \Drupal::entityTypeManager()
->getStorage('file');
$files = $fileStorage->loadMultiple();
$mediaStorage = \Drupal::entityTypeManager()
->getStorage('media');
// Enter user id to assign media
$uid = 1;
foreach ($files as $file) {
if (!$file->isPermanent()) {
continue;
}
$media = $mediaStorage->create([
'bundle' => 'image',
'uid' => $uid,
'name' => $file->getFilename(),
'field_media_image' => [
'target_id' => $file->id(),
'uuid' => $file->uuid(),
'alt' => $file->getFilename(),
'title' => $file->getFilename(),
],
]);
$media->save();
echo $file->id() .
' - ' .
$file->getFilename() .
' - ' .
$file->getFileUri() .
' - ' .
($media?$media->id():'no-media') .
PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment