-1

I want to remove certain element of breadcrumb on certain condition. I tried theme_preprocess_breadcrumb($variables). The condition and logic works fine here but doesn't reflect on viewing page. I tried this module_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb) – same issue. Code here doesn't reflect on viewing page, though printing variables in both methods gives me expected result but not on viewing page. I need help.

function theme_preprocess_breadcrumb($variables) {
// Removing last element of breadcrumb
if ( $variables['breadcrumb'] ) {  
$currentUrl = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; 
$key = 'find this';  
$countElements = count($variables['breadcrumb']);
if (strpos($currentUrl, $key) == true) {
  unset($variables['links'][$countElements-1]);
  unset($variables['breadcrumb'][$countElements-1]);
  kint($variables['breadcrumb']);kint($variables);die; 
}
}
return $variables;
}
12
  • 1
    Maybe start by explaining what breadcrumb you have right now, and what breadcrumb exactly you want. Then also include the code that didn't work. Please edit your question accordingly. Many thanks
    – leymannx
    Commented Dec 26, 2019 at 22:23
  • 1
    You should read the documentation for PHP's strpos function
    – Clive
    Commented Dec 27, 2019 at 11:58
  • 2
    You are not passing variables by reference. So the array is not being modified.
    – Kevin
    Commented Dec 27, 2019 at 12:13
  • 1
    Again, you need to add the & pass by reference, NOT a return. drupal.stackexchange.com/questions/209231/…
    – Kevin
    Commented Dec 27, 2019 at 13:05
  • 1
    @Kevin thanks it worked. for now
    – arpitk
    Commented Dec 27, 2019 at 18:50

1 Answer 1

4

As it mentioned in the comment section the $variables should passed by reference take a look at hook_preprocess_HOOK documentation page.
And also read about strpos to adapt your condition, here is an example of code to remove the last breadcrumb element in case url contain the word article for instance.

/**
 * Implements hook__preprocess_HOOK().
 */
function YOURTHEMENAME_preprocess_breadcrumb(&$variables) {
  // Removing the last element of the breadcrumb
  if ($variables['breadcrumb']) {
    $current_path = \Drupal::service('path.current')->getPath();
    // Get the real path even if it has an alias.
    $real_path = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
    $key = 'article';
    if (strpos($real_path, $key)) {
      // Remove the last element.
      array_pop($variables['breadcrumb']);
    }
  }
}
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.