0

I am trying to programmatically create a media object and a file, and then associate the file with the media object. The first part works--I can successfully create the media object and file. But the second part fails--the media object has no file associated with it.

Here is my code:

//Begin handling file uploads
$file = file_save_data('hey dude', 'public://2019-07/my_example.txt', FILE_EXISTS_REPLACE);

$media_arr = [
  'bundle' => 'file',
  'langcode' => 'en',
  'uid' => '0',
  'name'=> 'Test Name',
  'created' => date('U'),
  'changed' => date('U'),      
  'moderation_state' => 'published',
  'file' => [
    'target_id' => $file->id(),
  ],
];

$drupalMedia = Media::create($media_arr);

$drupalMedia->setName('Test Media Object')
  ->setPublished(TRUE)
  ->save();   

my_example.txt is created in the files directory, and the media object "Test Media Object" is also created, and I'm able to attach it to a node. But there is no file in the new media object! Am I missing something here?

1 Answer 1

1

Ah, I always figure it out after I say I can't do it. Once I specified the document type, it worked:

$media_arr = [
  'bundle' => 'file',
  'langcode' => 'en',
  'uid' => \Drupal::currentUser()->id(),
  'created' => date('U'),
  'changed' => date('U'),      
  'moderation_state' => 'published',
  'field_file_document_type' => 1409, //1409 is the id for pdf
  'field_media_file' => [
    'target_id' => $file->id(),
  ],
];

Edit: I should mention that 1409 is the id we use for pdfs, yours will be different. The field_file_document_type just needed to have a value in it to work.

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.