Score:0

How do redirect a user after login to a route that requires the UID?

ng flag

I know, this seems like a basic question:

In Drupal 9 how do I redirect a user after logging in to a path/route that requires the UID in the path?

I've researched and tried different implementations but none of them support tokens (Rules, Redirect After Login, etc.)

For example, after a user logs in they should land on "/homebox-page/dashboard/UID" <- numerical value from current user ID.

I was hoping for a simple module to handler this but it looks like I may need to do it through custom code?

Kevin avatar
in flag
This sounds like an event subscriber that checks if the user is logged in, if not redirect them and include the destination parameter so they return there once they log in.
berliner avatar
bd flag
As you didn't list it explicitly: [Login Destination](https://www.drupal.org/project/login_destination) seems to support tokens.
quantumized avatar
ng flag
Thank you. I think I'll go with custom code rather than Login Destinate which includes too much extra functionality that a few lines of code can handle.
Score:1
cn flag

This should be possible with a few lines of custom code. The user login form redirects already to entity.user.canonical, which requires the UID:

  public function submitForm(array &$form, FormStateInterface $form_state) {

    if (empty($uid = $form_state->get('uid'))) {
      return;
    }
    $account = $this->userStorage->load($uid);

    // A destination was set, probably on an exception controller.
    if (!$this->getRequest()->request->has('destination')) {
      $form_state->setRedirect(
        'entity.user.canonical',
        ['user' => $account->id()]
      );
    }
    else {
      $this->getRequest()->query->set('destination', $this->getRequest()->request->get('destination'));
    }

    user_login_finalize($account);
  }
  

You could add your own submit handler doing the same, overwriting the redirect. There you can use \Drupal::currentUser() because user_login_finalize() in the core submit handler sets this service with the user just logged in.

quantumized avatar
ng flag
Thank you! Yes, I actually ended up going the submit handler route from hook_form_alter() and it's working perfect.
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.