Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[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();
@chloecorfmat

This comment has been minimized.

Copy link

@chloecorfmat chloecorfmat commented Mar 26, 2017

Hello,

I'm trying to create media entity programatically, but i don't how to set field values. For example, i have a field_description and when i try the code below, the value is saved in database. But when i display the edit form of the media, the value is not in the field.

$media->field_description->value = 'value'; $media->save();

Can you explain me, why doesn't it work ?

Thank you. I hope my english was not so bad.

@hiramanpatil

This comment has been minimized.

Copy link

@hiramanpatil hiramanpatil commented May 15, 2017

Hi,

I am using 'media_entity_twitter' module to store the twitter URL and username using admin UI. I want to insert this tweet entity using drupal 8 custom module.

Any help?

Thanks

@Mark-Kiss

This comment has been minimized.

Copy link

@Mark-Kiss Mark-Kiss commented Jul 20, 2017

@chloecorfmat

Never use magic methods. They are unclear also not supported by IDE's. Use the content entity functions instead:

$media->set('field_description', $something);
$media->save;

The $something's structure depends on the field type. In case of simple text fields, it's just simple string. But if it's already a body field, probably it's going to be some nested array. Look examples in google, or try to find the field type itself in core.

@IT-Cru

This comment has been minimized.

Copy link

@IT-Cru IT-Cru commented Sep 1, 2017

Perhaps a better way to get you file mimetype:

\Drupal::service('file.mime_type.guesser')->guess($destination);

(from preCreate method of File entity)

@Adm94

This comment has been minimized.

Copy link

@Adm94 Adm94 commented Mar 29, 2018

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(),
],
@bhavesh-hirani

This comment has been minimized.

Copy link

@bhavesh-hirani bhavesh-hirani commented Mar 10, 2020

Hi,

This is what I have

$name = basename($xml_record->image);
            $destination = "public://$name";
            $file = file_save_data(file_get_contents($xml_record->image), $destination, FILE_EXISTS_REPLACE);

            $image_media = Media::create([
              'bundle' => 'image',
              'uid' => \Drupal::currentUser()->id(),
              'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
              'field_image' => [
                'target_id' => $file->id(),
                'alt' => $name,
                'title' => $name
              ],
            ]);
            $image_media->setName($name)->setPublished(TRUE)->save();

the result is below. The image does not get attached. It is uploaded though. I am running Drupal 8.6.10 and php 7.4.1

Screen Shot 2020-03-10 at 3 21 41 pm

@bhavesh-hirani

This comment has been minimized.

Copy link

@bhavesh-hirani bhavesh-hirani commented Mar 10, 2020

Thanks @Adm94. I tried what you said and it now works fine. Thanks a lot.

@ChristopheCaron

This comment has been minimized.

Copy link

@ChristopheCaron ChristopheCaron commented Mar 18, 2020

You can directly pass the file Entity when you create the media like this :

$image_media = Media::create([
'bundle' => 'image',
'uid' => \Drupal::currentUser()->id(),
'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
'field_image' => $file
]);

@mhentry

This comment has been minimized.

Copy link

@mhentry mhentry commented May 5, 2020

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.

@ChristopheCaron

This comment has been minimized.

Copy link

@ChristopheCaron ChristopheCaron commented May 6, 2020

To avoid duplicate in the media browser, you can use the form display entity reference autocomplete.

@mhentry

This comment has been minimized.

Copy link

@mhentry 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

This comment has been minimized.

Copy link

@Romaixn 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