I am trying to programmatically add an image field value to a paragraph.

The field value of the image is as below

Array (
  [target_id] => 28
  [alt] => test images
  [title] =>
  [width] => 1440
  [height] => 557

This is, how I try to set the image field value:

$paragraph->set('field_image',  $para_array);

The image field is not being set. Where am I going wrong and what will be the way to implement it?

  • do you have a paragraph ? – vinhdv Aug 22 '18 at 3:04
  • Did your image exit? Did you use $paragraph = Paragraph::create([]) before use $paragraph->set and why not add image to array in Paragraph::create? – MrD Aug 22 '18 at 3:15
  • The above snippet works , the error was caused by parent for loop . – Aditya Joshi Aug 22 '18 at 16:22

Don't set the complete array. You have to just pass target_id to set the image field:

use Drupal\paragraphs\Entity\Paragraph;

$paragraph = Paragraph::load($paragraph_id);
$paragraph->set('field_image',  $para_array['target_id']);
  • weight and height is computed, so those don't need to be set, but you do have to set alt/title. – Berdir Aug 22 '18 at 5:49

You can treat the field like a PHP array to add (and not replace) an image:

use Drupal\paragraphs\Entity\Paragraph;

  $paragraph = Paragraph::load($paragraph_id);
  $paragraph->field_image[] = [
    'target_id' => $fid,
    'alt' => $alt,
    'title' => $title,

You try the code.

    $images = [
      'target_id' => 1,
      'alt' => '',
      'title' => '',
    $paragraph = Paragraph::create([
      'type' => 'paragraph_type',
      'field_images' => $images

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.