create media entities and attach them to paragraphs in Drupal 8 & 9

0
(0)

Code snippet that can be used to create media entities and attach them to paragraphs in Drupal 8 & 9.

$directory = public://media;
$url = 'https://example.com/photo.jpg';

if(file_prepare_directory($directory, FILE_CREATE_DIRECTORY)) {
  $file = system_retrieve_file(trim($url), $directory, true);
}

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

$media->setPublished(TRUE)->save();

$paragraph = Paragraph::create([
  'type' => 'image',
  'field_media' => array(
    'target_id'  =>  $media->id(),
  )
]);
$paragraph->save();

Similar Posts:

957

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Scroll to Top