Programatically adding content - Core Media images

Submitted by jon on Sun, 01/12/2019 - 21:48

Programatically adding content - Core Media images

In trying to build a fully repeatable Drupal 8 site build, as well as wanting to include config, modules and themes, I want to be to insert content. This will allow boiler-plate or test content to be inserted, or will allow me to quickly build out a new version of my target site.  

In the first instance I was looking for a way to insert a image into a Core Media Image node.

For more long-standing entities (normal content nodes) the migrate module & friends would probably do what I needed, but at the time of writing, support for Core Media is still not really comprehensive (or that I could find, anyway), so I sought another way.

I got to the following snippit of PHP that, when run with something like drush, will insert an image file (e.g. jpeg) into a core media image content type called gallery_image. 

use Drupal\media\Entity\Media $image_data = file_get_contents("../assets/image_1.jpg");

$file_image = file_save_data($image_data, 'public://image_1.jpg', FILE_EXISTS_REPLACE);

$media_image = Media::create([ 'bundle' => 'gallery_image', 'name' => "Stripes 1", 'field_media_image' => [ 'target_id' => $file_image->id(),'alt'=> 'stripes 1'],]);


Note: This was against Drupal 8.6.10.