Skip to main content
Category:

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

 

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();

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook