Jun 04, 2020 in Drupal 8

Sometimes it is needed for a user to be redirected after registration. The user is not logged in yet, and has to go to a landing page with more instructions on verifying his e-mail. Thanks to this useful post I found out how to do it correctly and keeping the welcome message to show up.

/*
 * Allow redirect upon register
 */
function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  foreach (array_keys($form['actions']) as $action) {
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
      $form['actions'][$action]['#submit'][] = 'MYMODULE_redirect_new_registered_users';
    }
  }
}

/*
 * Redirection
 */
function MYMODULE_redirect_new_registered_users($form, FormStateInterface &$form_state) {
  $form_state->setRedirect('entity.node.canonical', ['node' => 'LANDING_PAGE_NID']);
}