0

How can I get the URL of an entity without its alias?

This code just gives me the path alias, but what I actually want would be, for example, /en/node/1 instead of /en/node/my-title.

$entity->toUrl('canonical', ['absolute' => true, language' => $entity->language()])
  ->toString(true)
  ->getGeneratedUrl());

1 Answer 1

3

You can add the option 'alias' => TRUE to your route. See how the shortlink is tested in core

  // \Drupal\Tests\node\Functional\NodeViewTest
  public function testLinkHeader() {
    $node = $this->drupalCreateNode();

    $expected = [
      '<' . Html::escape($node->toUrl('canonical')->setAbsolute()->toString()) . '>; rel="canonical"',
      '<' . Html::escape($node->toUrl('canonical', ['alias' => TRUE])->setAbsolute()->toString()) . '>; rel="shortlink"',
    ];

    $this->drupalGet($node->toUrl());

    $links = $this->getSession()->getResponseHeaders()['Link'];
    $this->assertEquals($expected, $links);
  }
1
  • Yes that works fine, thanks a lot :-)
    – Sebastian
    May 24, 2022 at 12:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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