Score:0

How do I unset a link?

gr flag

I want to programmatically decide whether to render a link or not. This should apply to all links e.g anchor tags (no wysywigs) Not only menu links.

I tried using hook_link_alter.

/**
 * Implements hook_link_alter().
 */
function mymodule_link_alter(&$variables) {
  $my_logic = TRUE;
  if ($my_logic) {
    // Any way to not render the link?
    // I tried:
    // $variables = []; and unsetting keys with no luck
    // $variables['options']['#access'] = FALSE; With no luck.
    // I guess i could set a flag here and somewhere else process it, but where?
  }
}

I can alter the structure, but I don't see any way to unset the element. What I want is basically to not render the element if $my_logic.

I also tried to use a service with the path_processor_outbound tag, but I have the same problem. I can "access" all generated links but can just alter / modify the output of processOutbound() but not to not process.

I think I can´t use a custom access check because i don´t want the url´s to be inaccessible if directly requested and I rather don´t want to do the check in a template

Kevin avatar
in flag
Unsetting a link wont make the path inaccessible FYI - you need permissions or access control for that.
john Smith avatar
gr flag
@Kevin Thx for pointing that out, actually custom-access might be a way to go, it´s not a requirement to be inaccessible, i just dont want to render the path and it´s link element into the source
Score:0
dk flag

I couldn't find a way to prevent the link from rendering, but I did find a couple of ways of hiding it, which was good enough in my use case.

  • Add a 'hidden' class to the link (along with CSS to display:none it)
  • Set the link text to an empty string.
  $item['options']['attributes']['class'][] = 'hidden';
  $item['text'] = "";

If your goal is just to tidy up a menu/hide a link rather than prevent access to the destination page then this might help.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.