Helper function to create paragraph image.
string $url: External URL of an image.
string $filename: Local file name of an image.
string $title: Image title.
string $alt: Image alt. If not set $title value will be used.
\Drupal\Core\Entity\EntityInterface Paragraphs image entity.
function _paragraphs_collection_demo_create_image_paragraph($filename, $title, $alt = NULL) {
// Create image from module files.
\Drupal::service('file_system')
->copy(\Drupal::service('extension.list.module')
->getPath('paragraphs_collection_demo') . '/files/' . $filename, 'public://' . $filename);
$image = File::create([
'uri' => 'public://' . $filename,
]);
$image
->save();
// Image paragraph type.
$image_paragraph = Paragraph::create([
'type' => 'image',
'paragraphs_image' => [
'target_id' => $image
->id(),
'alt' => empty($alt) ? $title : $alt,
'title' => $title,
],
]);
$image_paragraph
->save();
return $image_paragraph;
}