I am trying to add create a piece of new media with the following code. When visiting the media overview screen the media item is listed along with a thumbnail however when you edit the media item the file is not attached, although the file exists in the files area?

use Drupal\Core\Language\Language;
use Drupal\media_entity\Entity\Media;

$data =     file_get_contents("https://homepages.cae.wisc.edu/~ece533/images/airplane.png");
$file = file_save_data($data, 'public://plane.jpg',  FILE_EXISTS_RENAME);

$image_media = Media::create([
  'bundle' => 'image',
  'uid' => '1',
  'langcode' => Language::LANGCODE_DEFAULT,
  'status' => Media::PUBLISHED,
  'field_image' => [
    'target_id' => $file->id() ,
    'alt' => t('this is the alt text'),
    'title' => t('this is an image'),
  • What happens when you load image_media directly after the save ? Is the file target_id there ?
    – taggartJ
    Dec 20, 2016 at 8:58
  • Directly after the save the target_id is present and correct, however if i reload the media entity again straight away via Media::load the field is no longer attached.
    – Rob Holmes
    Dec 20, 2016 at 10:08

1 Answer 1


Unless you have a default language setup, Language::LANGCODE_DEFAULT will resolve to x-default.


  • Set a default language
  • Set the property manually, e.g, 'en' rather than Language::LANGCODE_DEFAULT
  • Remove the line entirely

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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