|$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'),|
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.
Can you explain me, why doesn't it work ?
Thank you. I hope my english was not so bad.
Never use magic methods. They are unclear also not supported by IDE's. Use the content entity functions instead:
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.
Don't you need to set the
This is what I have
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
You can directly pass the file Entity when you create the media like this :
$image_media = Media::create([
Thanks a lot, that worked with "thumbnail"