3

in Drupal 7 I could just use array_pop($breadcrumb), but in Drupal 8 the breadcrumb is an object and I don't see a method for removing the last element.

How can this be done?

7

Drupal 7 and Drupal 8 are more or less the same in some aspects.

If you use preprocess_breadcrumb in your theme, you would do

function my_theme_preprocess_breadcrumb(&$variables) {
  array_pop($variables['breadcrumb']);
  ...
}

You could also solve this in the template file, by skipping the first item in {{ breadcrumb }}

If you want module only solution, you could swap the breadcrumb service with your own thing.

| improve this answer | |
  • Is it $variables['breadcrumb'] or $variables['links']? – kiamlaluno Apr 11 '17 at 9:15
  • @kiamlaluno $variables['breadcrumb'] is the correct one, links is what the original preprocess uses to generate the breadcrumb. Any theme overwriting it will act after this has happened, so they should alter breadcrumb instead of links. – googletorp Apr 11 '17 at 9:47
  • Thank you. I was just checking the approved suggestion edit (which was not approved by you) was correct, since it was changing the meaning of the answer. – kiamlaluno Apr 11 '17 at 11:06
0

If you are using a BreadcrumbBuilder, and try to remove a Link already added, you can't. Unless you create a custom Breadcrumb class, to add a new method or override an existing one.

My solution was this :

<?php

namespace Drupal\my_module;

use Drupal\Core\Breadcrumb\Breadcrumb;

/**
 * Blablabla.
 */
class BreadcrumbCustom extends Breadcrumb {

  /**
   * Sets the breadcrumb links.
   *
   * @param \Drupal\Core\Link[] $links
   *   The breadcrumb links.
   * @param bool $force
   *   Boolean to indicate if you should force to override the existing links.
   *   Use with caution.
   *
   * @return $this
   *
   * @throws \LogicException
   *   Thrown when setting breadcrumb links after they've already been set.
   */
  public function setLinks(array $links, $force = FALSE) {
    if (!empty($this->links) && !$force) {
      throw new \LogicException('Once breadcrumb links are set, only additional breadcrumb links can be added.');
    }

    $this->links = $links;

    return $this;
  }

}

and inside the BreadcrumbBuilder :

$links = $breadcrumb->getLinks();
unset($links[1]);
$breadcrumb->setLinks($links, TRUE);
| improve this answer | |
  • The parameter force does not exist anymore (at least in 8.5.5). – Philipp Michael Jul 16 '18 at 15:04
  • Since it's a custom class, with override of a method, it doesn't matter ^^ – Pierre Noel Jul 17 '18 at 8:08
  • Ah, sorry for that. Of course you are right. I thought you were talking about the core breadcrumb. – Philipp Michael Jul 17 '18 at 13:49

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.