1

I have a node with an array of multiple languages.

 [19] => Drupal\node\Entity\Node Object
        (
            [in_preview] => 
            [values:protected] => Array
                (
                    [vid] => Array
                        (
                            [x-default] => 19
                        )

                    [langcode] => Array
                        (
                            [x-default] => en
                            [ca] => ca
                        )

I'm getting its url as:

$options = array('absolute' => TRUE);
$link = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $key], $options);

print($link) is giving me http://test-d8.local/en/node/19 where as I want url of "ca" language not "en" language. i.e. http://test-d8.local/ca/node/19

Is there any way that gives node translations of particular langcode?

This line $language = $entity->get('langcode')->value; is giving me the value of chosen language from select list.

3

You want to use toUrl() with the language option.

$node->toUrl('canonical', ['language' => $node->language()]);

Unfortunately, toUrl() currently doesn't automatically respect the active language.

  • $node->toUrl('canonical', ['language' => $node->language()]; is not working. I added $node->toUrl('canonical', ['language' => $node->language()]->toString(); Now its giving /en/node/19 not even absolute url. – Sugandh Khanna Jun 21 '16 at 9:32
  • To make it absolute you can use the setAbsolute method $url->setAbsolute(TRUE) – Eyal Jun 21 '16 at 13:07
2
$language = 'ca';
$link = $value->getTranslation($language)->url();
$title =  $value->getTranslation($language)->title->value;

this worked for me.

1

You can get the translation of the node like this:

$node = $node->getTranslation('ca');

And, depending what you need, you can get the link or url like this:

$link = $node->toLink();
$url = $node->toUrl();
  • Doesn't actually work like that AFAIK, see my answer. – Berdir Jun 21 '16 at 9:18
  • I have tried this, but $node = $value->getTranslation('ca'); $link = $node->toUrl(); print_r($link);die; is giving a 404 infinite loop. – Sugandh Khanna Jun 21 '16 at 9:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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