I am still trying to wrap my head around some of the D8 things. Working with some media bundles like media_audio_bundle and need to write some migration scripts. I have spent couple of days now researching and trying everything but nothing seems to work.

Its like Drupal wall all over again.

This is the closest I came:

$audio = \Drupal::entityTypeManager()
            'type' => 'media', 
            'bundle' => 'audio', 
            'title' => 'Another Audio', 
            'field_audio_file' => 11

It seems to create some sort of media object but does not save it.

If somebody can help, would be much appreciated.

use Drupal\media_entity\Entity\Media;

$image_data = file_get_contents("URL OF FILE");
$file_image = file_save_data($image_data, 'public://FILENAME', FILE_EXISTS_REPLACE);
$media_image = Media::create([
  'bundle' => 'image',(YOUR BUNDLE)
  'name' => "FILENAME",
  'field_image' => [
    'target_id' => $file_image->id(),

Try this one, maybe this will help.


You should invoke save method to save the entity to database.

  • For some reason this would throw an error for me. Nov 14 '16 at 4:54

Not sure if this is the best way, but it seems to work.

$media =  Drupal\media_entity\Entity\Media::create([
 'bundle'        => 'audio',
 'name'       => 'demo audio',
 'field_audio' => [
      'target_id' => $file->id(),

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.