[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
|$filesystem = \Drupal::service('file_system');|
|// Create file entity.|
|$image = File::create();|
|$image->setMimeType('image/' . pathinfo($destination, PATHINFO_EXTENSION));|
|// 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'),|
May 6, 2020
To avoid duplicate in the media browser, you can use the form display entity reference autocomplete.
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.
Oct 5, 2020
Don't you need to set the
field_media_imagekey 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
Hi, is it possible to load existing media image into a media field ? I used Media::create but the problem is, its creating duplicate in the media browser, I tied Media::load with the media id of the image, no luck.
any assistance would be really helpful.