I'd like to show/hide a main-menu link based on a $tempStore variable the user can set and modify during their session, i.e.

  • user sets $tempStore['vlaue'] = 0; --> menu link is hidden
  • user sets $tempStore['value'] = 1; --> menu link is shown.

The menu link is provided by a view (page). What I started to do is to implement my own custom RouteSubscriber which adds a custom access check (which is defined as a service in mymodule.service.yml) to the view. The custom access check in myCustomAccessCheck.php basically does the following

   $value = $tempstore->get('value');
   return AccessResultAllowed::allowedIf($value == 1);

Apparently Drupal by default hides all menu links that the user does not have access to, so this approach should work (which it actually does!). However, caching is a problem, i.e. when the user changes the value, the link is shown/hidden only after a cache-rebuild.

Now my question:

  • Is there a better/more elegant approach to do this? (I could not find any)
  • If not, can I use some hook to add my custom cache tag to the menu-link? (the view itself already has this cache tag, but the provided menu link does not respond to it)
  • Is it "better" to make a view-block instead of view-page, using a hook to add the custom cache tag to the block and add the block to the menu via *.links.menu.yml to have more control over the behavior?

You can try to add the custom cache tag to the access result:

return AccessResult::allowed()->addCacheTags(['custom_cache_tag']);
return AccessResult::forbidden()->addCacheTags(['custom_cache_tag']);

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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