Drupal 8: Redirecting a form based on a field value.

Profile picture for user Phil Frilling
By Phil Frilling, 8 November, 2016
I needed to redirect the user register form based on a role that the user wanted to apply for. To do this, I added a custom submit handler to the register form.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYTHEME_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'MYTHEME_custom_form_submit';
}

function MYTHEME_custom_form_submit($form, Drupal\Core\Form\FormStateInterface $form_state){
  // Get the value of the radio button that the user selected.
  if ($form_state->getValue('roles') == 'ROLE_ID') {
    $url = \Drupal\Core\Url::fromUserInput('/node/269');
  }
  else {
    $url = \Drupal\Core\Url::fromUserInput('/node/300');
  }
 }
  $form_state->setRedirectUrl($url);
}