1

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

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();
  • 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 Feb 11 at 19:13
  • 1
    @Rick, see drupal.stackexchange.com/a/227182/47547 how to lookup or create a file id for the image URL. – 4k4 Feb 11 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 Feb 12 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 Feb 12 at 16:15
  • Thanks a lot. the link you gave me helped to finish this task. :) – Rick Feb 13 at 22:05
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, privacy policy and cookie policy

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