Showing local tasks in toolbar with hook_toolbar: caching problem

I’m creating a module using the toolbar api showing all administrative functions in a more compact toolbar. I’m having “cache” troubles showing the local tasks in the toolbar… How can I keep these items outside the toolbar cache?

In my custom module I use hook_toolbar to add the local tasks

/**  * Implements hook_toolbar().  */ function compact_toolbar_toolbar() {      $items = [];     ...      $tasks = _compact_toolbar_local_tasks();     $items = array_merge($items,$tasks);      return $items; } 

And a function to generate the toolbar local tasks…

/**  * Create local tasks toolbar items  */ function _compact_toolbar_local_tasks() {      $items = [];     $route = Drupal::routeMatch()->getRouteName();     $manager = Drupal::service('');     $primary = $manager->getLocalTasks($route, 0);      foreach($primary['tabs'] as $key => $tab) {          // add toolbar tab         $items[$key] = [             '#type' => 'toolbar_item',             '#cache' => [ // Can I overrule the toolbar cache here?                 'max-age' => 0,              ],             'tab' => [                 '#type' => 'link',                 '#title' => $tab['#link']['title'],                 '#url' => $tab['#link']['url'],                 '#access' => $tab['#access'],                 '#attributes' => [                     'title' => $tab['#link']['title'],                 ],             ],             '#weight' => $tab['#weight'],         ];          // check if task is active         if($tab['#active']) {             $items[$key]['tab']['#attributes']['class'][] = 'is-active';         }          // get secondary tabs for each primary tab         $route = $items[$key]['tab']['#url']->getRouteName();         $secondary = $manager->getLocalTasks($route, 1);          // get secondary tabs as tray         if (!empty($secondary['tabs'])) {              $links = [];             $items[$key]['tab']['#attributes']['class'][] = 'toolbar-parent';               // create renderable array of secondary links             foreach ($secondary['tabs'] as $skey => $stab) {                 $sname = substr($skey, strrpos($key, '.') + 1);                 $links[$sname] = [                     'type' => 'link',                     'title' => $stab['#link']['title'],                     'url' => $stab['#link']['url'],                 ];             }              // add tray with secondary tasks             $items[$key]['tray'] = [                 '#heading' => t('Secondary tasks'),                 'toolbar_secondary_tasks' => [                     '#theme' => 'links__toolbar',                     '#links' => $links,                     '#attributes' => ['class' => ['toolbar-menu']],                 ],             ];          }      }      return $items; } 

When I disable the cache in hook_page_top in core/modules/toolbar/toolbar.module everything works like a charm. Otherwise my custom items won’t follow the current page…

/**  * Implements hook_page_top().  *  * Add admin toolbar to the top of the page automatically.  */ function toolbar_page_top(array &$page_top) {   $page_top['toolbar'] = array(     '#type' => 'toolbar',     '#access' => Drupal::currentUser()->hasPermission('access toolbar'),     /*     '#cache' => [       'keys' => ['toolbar'],       'contexts' => ['user.permissions'],     ],     */   ); } 

Can I overrule the toolbar cache by using the #cache array in my custom toolbar items? Which tags/context should I use?

This is how the toolbar looks like with my compact_toolbar module enabled… (but toolbar cache disabled) I really like the result! – I also made the menu behave like a simple dropdown menu and added a “content menu” to quickly add new content…

Compact toolbar example

Sponsored by SupremePR
This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Showing local tasks in toolbar with hook_toolbar: caching problem

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.