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:
- how to Programmatically update an entity reference field in Drupal 8 & 9
- How to apply Drupal Patch
- How to create a custom page programmatically in Drupal 8
- change canonical URL in drupal 8 & 9
- Make modules and themes compatible with drupal 9
1,106