2

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?

3
  • do you have a paragraph ?
    – vinhdv
    Commented Aug 22, 2018 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
    Commented Aug 22, 2018 at 3:15
  • The above snippet works , the error was caused by parent for loop . Commented Aug 22, 2018 at 16:22

3 Answers 3

2

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,
  ];
  $paragraph->save();
5
  • Where to add the image location URL? How will the image URL be stored on the backend? Is just the Alt enough for inserting image?
    – Rick
    Commented Feb 11, 2020 at 19:13
  • 1
    @Rick, see drupal.stackexchange.com/a/227182/47547 how to lookup or create a file id for the image URL.
    – 4uk4
    Commented Feb 11, 2020 at 19:54
  • thanks. I am trying to select image from my SQL table and push into Drupal. this is my ticket - drupal.org/project/paragraphs/issues/3113055
    – Rick
    Commented Feb 12, 2020 at 16:14
  • what is target_id here? How can I find that or set that for my image? can i create a column on my table as target id, and map it?
    – Rick
    Commented Feb 12, 2020 at 16:15
  • Thanks a lot. the link you gave me helped to finish this task. :)
    – Rick
    Commented Feb 13, 2020 at 22:05
1

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']);
$paragraph->save();
1
  • weight and height is computed, so those don't need to be set, but you do have to set alt/title.
    – Berdir
    Commented Aug 22, 2018 at 5:49
0

You try the code.

    $images = [
      'target_id' => 1,
      'alt' => '',
      'title' => '',
      'width'=>1440,
      'height'=>557
    ];
    $paragraph = Paragraph::create([
      'type' => 'paragraph_type',
      'field_images' => $images
    ]);
    $paragraph->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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