3

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.

1
  • 2
    See the answer from @sonfd and override getRouteParameters() to return the parameter array with the node id.
    – 4uk4
    Commented Aug 10, 2021 at 16:44

1 Answer 1

6

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();
}
1
  • 1
    Thanks! I just had to amend it slightly to make it work. See updated questing for working version. Commented Aug 11, 2021 at 6:38

Your Answer

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

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