Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@steffenr
Last active February 27, 2023 18:33
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save steffenr/a40bab1f3b1c066d5c0655351e2107fd to your computer and use it in GitHub Desktop.
Save steffenr/a40bab1f3b1c066d5c0655351e2107fd to your computer and use it in GitHub Desktop.
[Drupal 8] Create file/ media_entity programmatically
<?php
$filesystem = \Drupal::service('file_system');
// Create file entity.
$image = File::create();
$image->setFileUri($destination);
$image->setOwnerId(\Drupal::currentUser()->id());
$image->setMimeType('image/' . pathinfo($destination, PATHINFO_EXTENSION));
$image->setFileName($filesystem->basename($destination));
$image->setPermanent();
$image->save();
// Create media entity with saved file.
$image_media = Media::create([
'bundle' => 'image',
'uid' => \Drupal::currentUser()->id(),
'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
'status' => Media::PUBLISHED,
'field_image' => [
'target_id' => $image->id(),
'alt' => t('Placeholder image'),
'title' => t('Placeholder image'),
],
]);
$image_media->save();
@mhentry
Copy link

mhentry commented May 7, 2020

Hi Chris, thank you for the reply. If I use autocomplete it will difficult for the editor to browse the existing image they required.

@Romaixn
Copy link

Romaixn commented Oct 5, 2020

Don't you need to set the thumbnail and field_media_image key in the Media entity too ?
For my case, without that, my media entity was associated with a default file.

"thumbnail" => [
     "target_id" => $file->id(),
     "alt" => $file->getFilename(),
],
"field_media_image" => [
    "target_id" => $file->id(),
     "alt" => $file->getFilename(),
],

Thanks a lot, that worked with "thumbnail" 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment