10

I'm trying to programmatically create a media file. Here's what I got so far:

$file_data = file_get_contents('http://www.africau.edu/images/default/sample.pdf');

$file = file_save_data($file_data, 'public://3010.pdf', FILE_EXISTS_REPLACE);

$media = Media::create([
  'bundle' => 'file',
  'uid' => '0',
  'field_media_file' => [
    'target_id' => $file->id(),
  ],
]);

$media->setName('Hello')
  ->setPublished(TRUE)
  ->save();

Unfortunately this returns me the following error and the media file doesn't get saved:

Error: Call to a member function getSource() on null in Drupal\media\Entity\Media->getSource() (line 138 of core/modules/media/src/Entity/Media.php).

What am I doing wrong? How can I fix this error?

0

3 Answers 3

10

uid shouldn't be 0, just change 'uid' => '0' by 'uid'=> \Drupal::currentUser()->id():

$file_data = file_get_contents('http://www.africau.edu/images/default/sample.pdf');
$file = file_save_data($file_data, 'public://3010.pdf', FILE_EXISTS_REPLACE);
$media = Media::create([
  'bundle'           => 'file',
  'uid'              => \Drupal::currentUser()->id(),
  'field_media_file' => [
    'target_id' => $file->id(),
  ],
]);
$media->setName('Hello')->setPublished(TRUE)->save();
6

Things have changed a bit since the advent of Drupal 9 and the Media module in core. Notice that the bundle is now 'document'. You can find the media types at /admin/structure/media: Hover your mouse over the edit button and you'll see the media type in the URL.

$file_data = file_get_contents('http://www.africau.edu/images/default/sample.pdf');
$file = file_save_data($file_data, 'public://3010.pdf', FileSystemInterface::EXISTS_REPLACE);
$media = Media::create([
  'bundle'=> 'document',
  'uid' => \Drupal::currentUser()->id(),
  'field_media_document' => [
    'target_id' => $file->id(),
  ],
]);

$media->setName('3010 Sample PDF')
  ->setPublished(TRUE)
  ->save();
0

TL;DR Use \Drupal::service('file.repository')->writeData() instead of file_save_data in Drupal 10

I got Call to undefined function Drupal\custom_module\Commands\file_save_data()

Here's the change record: https://www.drupal.org/node/3223520

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.