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?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityin 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?
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.
$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.
Apr 11, 2017 at 9:47
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);