Drupal - How do I programmatically remove one breadcrumb link?
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.
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);