0

I need to get some values from a custom block I've created, and I am using the following code.

// Get the block
$block = \Drupal\block\Entity\Block::load('hightlight');

// Get the block content
$uuid = $block->getPlugin()->getDerivativeId();
$block_content = \Drupal::service('entity.repository')->loadEntityByUuid('block_content', $uuid);

// Get the field value
$field = $block_content->get('field_link')->getValue()[0];

The problem is that the field contains entity:node/9. Is it possible to convert that value in a link?

This is the content of the field.

screenshot

  • Why not render the field? If you want to get the url to build your own link then use getUrl(), see drupal.stackexchange.com/questions/267497/… – 4k4 Apr 24 at 9:34
  • The problem is that it doesn't like a normal link field, I can't use the getUrl() function, I've added a screenshot of the dump of my variable – user93063 Apr 24 at 9:37
  • The properties you've just added to the question look like a normal link field and then you can apply the method getUrl() to compute the URL object. – 4k4 Apr 24 at 9:44
  • When I use the getUrl() I got this error : Error: Call to a member function getUrl() – user93063 Apr 24 at 9:54
0

You have to rewrite

$value = $block_content->get('field_link')->getValue()[0];

to something like this:

$value = $block_content->get('field_link')->first()->getUrl()->toString();

See What is the correct way to get the link url?

  • Thanks it works ! – user93063 Apr 24 at 10:08

Your Answer

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