Last active
February 27, 2023 18:33
Star
You must be signed in to star a gist
[Drupal 8] Create file/ media_entity programmatically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a lot, that worked with "thumbnail" 👍