Skip to main content

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

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.

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

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


Comments