Score:2

What is the route for a specific node?

kz flag

I want to override the user.login route that points to the default login page.

I.e. I want that a user who presses the default "Log in" link for the site to be directed to a node that provides some help (where the user can click on a link and arrive at the standard log-in form).

Say that the path I want to redirect to is /node/42. How can I find out what route to return for a specific node?

I believe that the right place to do this in Drupal 9 is to override the getRouteName() function the in the LoginLogoutMenuLink class. So I'm trying to create something like this.

public function getRouteName() {
  if ($this->currentUser->isAuthenticated()) {
    return 'user.logout';
  }
  else {
    return '- What to put here? - ';
  }
}

I've searched a lot, and some people say that the route for nodes are entity.node.canonical. But that does not solve it for me. I think that the route for a specific node also need to have the nid in there somewhere.

4uk4 avatar
cn flag
See the answer from @sonfd and override `getRouteParameters()` to return the parameter array with the node id.
Score:6
in flag

Unless something is overriding the routing, the route for all nodes is entity.node.canonical.

The route needs a route_parameter, node, to pass the nid.

For example, you could create a link to a node's page with Link::createFromRoute() like:

$my_link = Link::createFromRoute('My link text', 'entity.node.canonical', [
  'node' => 123,
]);

As @4k4 pointed out, you'll need to create the LoginLogoutMenuLink class's getRouteName() and getRouteParameters() methods.

public function getRouteName() {
  if ($this->currentUser->isAuthenticated()) {
    return 'user.logout';
  }
  else {
    return 'entity.node.canonical';
  }
}

public function getRouteParameters() {
  // Not sure if this is the best conditional to use here.
  if ($this->getRouteName() == 'entity.node.canonical') {
    return [
      'node' => 123,
    ];
  }

  return parent::getRouteParameters();
}
Free Radical avatar
kz flag
Thanks! I just had to amend it slightly to make it work. See updated questing for working version.
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.