2

I am trying to insert tag url and page title in breadcrumb path. With page title everything is Ok, however I can't find any info how to get tags, or how to generate url for them. I think I am getting tag how I am supposed to, but this returns object of Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem without id (?). So How could I gennerate Url from this object?

function theme_preprocess_breadcrumb(&$vars) {
  $node = \Drupal::request()->attributes->get('node');
  $title = $node->getTitle();

  $tag = $node->field_tags->first();

  $vars['breadcrumb'][] = [
      'text' => $title
  ];
}
  • Look for implementations of \Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface – user21641 Dec 29 '15 at 19:11
2

Yes, I agree with Ivan.

Here is a blog post that recommends creating a new breadcrumb builder service. https://www.palantir.net/blog/d8ftw-breadcrumbs-work

The key pieces are extending BreadcrumbBuilderBase and defining the service in a yml file.

 # mymodule.services.yml 
 services:   mymodule.breadcrumb:
   class: Drupal\mymodule\NewsBreadcrumbBuilder
   tags:
     - { name: breadcrumb_builder, priority: 100 }

While data can be manipulated in the preprocess layer it should be used for visual changes rather than behavioral changes.

Now to answer your more direct question of how to actually generate the links. I think what you want is something like

$node->field_tags->referencedEntities()[0]->id();

I recommend looking at BookBreadcrumbBuilder both for the Breadcrumb specific parts and the link construction. There you'll see links constructed like this:

$links[] = Link::createFromRoute($parent_book->label(), 'entity.node.canonical', array('node' => $parent_book->id()));
1

This is the object of the first term entity in the fielditemlist of field_tags:

$node->field_tags->first()->entity

You can access all propterties of the term, for example the label or id:

$node->field_tags->first()->entity->id()
$node->field_tags->first()->entity->label()

Or the url:

$node->field_tags->first()->entity->url()

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.