Score:0

Get an entity URL, not its path alias

cn flag

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());
Score:3
ng flag

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);
  }
cn flag
Yes that works fine, thanks a lot :-)
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.