I would like to alter the link displayed on the language switcher for the second language of my site, for a certain node. Essentially when you viewing a certain node in the main language, and then use the language switcher to view the secondary language, I want the language switcher to serve a different link from the one that links to the translation of the node on the main language. (The design of this node is different from the one on the main language, so just translating the node won't help in this case)

I've tried both MYTHEME_preprocess_links__language_block(&$variables) and MYMODULE_language_switch_links_alter(array &$links, $type, \Drupal\Core\Url $url) but in both cases either the variable I was interested was protected or private or I couldn't get any interesting variables to work with.

Is it allowed to use these hooks above for what I'm after, or it needs to be a more hacky way?

  • Welcome to Drupal Answers :) What types of interesting variable(s) are you trying to find specifically? – Clive Feb 8 '19 at 13:02
  • I manage to go a bit further with the language_block function, I manage to get the intrnalPath by using: $variables['links']['ja']['link']['#url']->getInternalPath(); However the problem remains, as I can't find any way to alter the value of this internalPath. – user82025 Feb 8 '19 at 13:26
  • Have you tried replacing $variables['links']['ja']['link']['#url'] with a new \Drupal\Core\Url object that has the properties you need? – Clive Feb 8 '19 at 13:33
  • @leymannx This piece of code here, is explaining how to add additional classes to the language switcher, however, what I'm after, is to replace the link that leads to the node itself. Unless the way you do that is the same as with the class, have you tried it yourself? – user82025 Feb 8 '19 at 14:51
  • 1
    @Clive Yes, by replacing the link object in there, I mange to override my link and lead me to the node I wanted. Thank you so much. – user82025 Feb 8 '19 at 15:25

To wrap this up, here is the complete solution to this problem.

function mytheme_preprocess_links__language_block(&$variables) {
  $internal_path = $variables['links']['ja']['link']['#url']->getInternalPath();

  // In this case 'node/30074' is the translated node that will normally go to 
  if ($internal_path == 'node/30074') {

    // We need to create a new Url object with the node we need to redirect to
    $new_internal_path = Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => 30073], []);

    // ...and replace the original Url object  
    $variables['links']['ja']['link']['#url'] = $new_internal_path;

Thanks to Clive for pointing out the process for this problem.