0

I have a node with a field called "field_paragraph" which is a paragraph reference. Referencing a paragraph type which has a field called "field_image"

I'm trying to get the url of the field_image in a custom module and so far i have this. But i don't seem to get it work.

use Drupal\paragraphs\Entity\Paragraph; 
use Drupal\node\Entity\Node;
$node = Node::load($nid);
$paragraph_field = $node->get("field_paragraph")->getValue();
$paragraph = Paragraph::load($paragraph_field[0]['target_id']);

Here is where the problem occurs

$uri = $paragraph->field_image->entity->getFileUri();

The above returns nothing.

I used kint to print "$paragraph->field_image->entity" and it returns null. What I'm I doing wrong? I tried all answers I could find on here to no avail.

After getting the uri I think calling the below line would be enough.

$url = file_create_url($uri);

Question: How do I get the url of an image field in paragraphs programmatically?

  • There seems to be nothing wrong with the code. The first step is very verbose and the second a much shorter version. But both steps are basically the same, both are reference fields, to a paragraph and a file. So you can use in the second step the verbose version you used in the first step and debug the array if there is content in the image field, that means a target_id to the image file. – 4k4 Jun 19 '17 at 16:40
1

Your pretty much there but when calling the field name use the method get()

$uri = $paragraph->get('field_image')->entity->getFileUri();

Then once you have the uri you'll be able to get the full url

$url = file_create_url($uri);

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.