Skip to main content

Drupal 8: Change the user registration form to a multi-step form.

I was tasked with breaking the user registration form of a Drupal 8 installation into a multi-step form. This was necessary because depending on what a user selected in step one, they were shown different form fields in step two.

To begin, I added all of the fields I needed to the user profile using the GUI. (/admin/config/people/accounts/fields). Then, I added the fields I needed to the manage form display/register tab (/admin/config/people/accounts/form-display/register).

This gave me a working, one page registration form. So, the tricky part, how to break it apart into pages.

First, I searched for any contributed modules that are already doing this, but I couldn't find any that did the trick. So, I used Drupal Console and generated a custom module.

drupal generate:module

Next, I began writing a form alter implementation.

  1. /**
  2.  * Implements hook_form_FORM_ID_alter().
  3.  */
  4. function my_module_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  5. }

I needed to defined what page number I was starting with, so I added a $form_state variable to begin with:

  1. // If the form doesn't have a page_num defined, define it here.
  2. if (!$form_state->has('page_num')) {
  3.   $form_state->set('page_num', 1);
  4. }

Then, I created a multidimensional array of fields that I wanted on each page that looked like this:

  1. $pages = [
  2.   1 => [
  3.     'field_first_name',
  4.     'field_last_name',
  5.     'field_phone',
  6.     'mail',
  7.     'name',
  8.     'account',
  9.   ],
  10.   2 => [
  11.     'field_employer_address',
  12.     'field_employer_job_title',
  13.     'field_employer_type',
  14.     'field_seeker_interests',
  15.     'field_seeker_introduction',
  16.     'field_seeker_resume',
  17.     'actions',
  18.   ],
  19. ];

Once I defined the fields I wanted and on which page, I could then loop through that array and set the #access field to FALSE for the fields that are not on my current page.

I also needed to add a validation array to pass to our custom submit button later. This array contains the field names that are on the current page that need validated. Without validation of these fields, the submitted values are not in the $form_state variable upon submission.

  1. // Validate the fields of the appropriate steps.
  2. $validation = [];
  3.  
  4. // Disable all the fields to begin.
  5. foreach ($pages as $page => $fields) {
  6.   if ($page != $form_state->get('page_num')) {
  7.     foreach ($fields as $field) {
  8.       $form[$field]['#access'] = FALSE;
  9.     }
  10.   }
  11.   else {
  12.     foreach ($fields as $field) {
  13.       array_push($validation, [$field]);
  14.     }
  15.   }
  16. }

Then, I added a custom validation function and my next/back buttons to the form. More on the custom validation function later. The next/back buttons are pretty standard. Both have a custom submit handler. Notice the #limit_validation_errors on the next button. This allows us to inform the form to validate the fields that are submitted in this step.

  1. // Add our custom validation function to the start of the array.
  2. array_unshift($form['#validate'], 'my_module_user_register_pre_submit');
  3.  
  4. // Remove access to the roles selection.
  5. $form['job_seeker']['#access'] = FALSE;
  6. $form['employer']['#access'] = FALSE;
  7.  
  8. $form['my_module_actions'] = [
  9.   '#type' => 'actions',
  10.   '#weight' => 100,
  11. ];
  12.  
  13. $form['my_module_actions']['next'] = [
  14.   '#type' => 'submit',
  15.   '#value' => t('Next'),
  16.   '#submit' => [
  17.     'my_module_register_next_previous_form_submit',
  18.   ],
  19.   '#limit_validation_errors' => $validation,
  20.   '#access' => FALSE,
  21.   '#weight' => 1,
  22. ];
  23.  
  24. $form['my_module_actions']['previous'] = [
  25.   '#type' => 'submit',
  26.   '#value' => t('Back'),
  27.   '#submit' => [
  28.     'my_module_register_next_previous_form_submit',
  29.   ],
  30.   '#access' => FALSE,
  31.   '#limit_validation_errors' => [],
  32. ];

Then, I added a switch statement to handle any page specific form alterations:

  1. switch ($form_state->get('page_num')) {
  2.   case 1:
  3.     // Allow access to the pages on this page.
  4.     foreach ($pages[$form_state->get('page_num')] as $form_key) {
  5.       $form[$form_key]['#access'] = TRUE;
  6.     }
  7.  
  8.     $form['my_module_roles'] = [
  9.       '#type' => 'radios',
  10.       '#options' => $new_role_options,
  11.       '#title' => t('What type of account would you like to create'),
  12.       '#required' => TRUE,
  13.       '#weight' => 49,
  14.     ];
  15.  
  16.     // Enable our next button.
  17.     $form['my_module_actions']['next']['#access'] = TRUE;
  18.  
  19.     break;
  20.  
  21.   case 2:
  22.     $page_values = $form_state->get('page_values');
  23.  
  24.     // Add our previous buttons.
  25.     $form['my_module_actions']['next']['#access'] = FALSE;
  26.     $form['my_module_actions']['previous']['#access'] = TRUE;
  27.  
  28.     $role_selected = $page_values[1]['my_module_roles'];
  29.  
  30.     foreach ($pages[2] as $formkey) {
  31.       if (strpos($formkey, 'field_employer') !== FALSE) {
  32.         // Remove access from all field_employer fields if the role selected is
  33.         // not 'employer'.
  34.         $form[$formkey]['#access'] = ($role_selected == 'employer' ? TRUE : FALSE);
  35.       }
  36.       else if (strpos($formkey, 'field_seeker') !== FALSE) {
  37.         // Remove access from all field_seeker fields if the role selected is
  38.         // not 'job_seeker'.
  39.         $form[$formkey]['#access'] = ($role_selected == 'job_seeker' ? TRUE : FALSE);
  40.       }
  41.     }
  42.  
  43.     break;
  44. }

That pretty well takes care of the form_alter function.

The submit function to manage our next/back buttons is below. I started by getting the current page that was submitted and loading our $pages variable from the form_alter function. We also define a $page_values array that will store our paged submissions while we step through the form. We then act on the form based on which button the user selected. If next, we loop through the fields that should be on page one and save them to the $page_values array. Then we increment the current page. Lastly, we save the $page_values and $page_num to the $form_state and set the rebuild parameter to true.

  1. /**
  2.  * Custom form submit for the user registration form.
  3.  *
  4.  * @param $form
  5.  * @param \Drupal\Core\Form\FormStateInterface $form_state
  6.  */
  7. function my_module_register_next_previous_form_submit($form, Drupal\Core\Form\FormStateInterface $form_state) {
  8.  
  9.   // Get the current page that was submitted.
  10.   $current_page = $form_state->get('page_num');
  11.  
  12.   // Get the fields for the pages.
  13.   // These are the same as the $pages variable in the form_alter.
  14.   // I've excluded them here for brevity.
  15.   $fields = [...];
  16.  
  17.   // Setup our page values variable.
  18.   if (!$form_state->get('page_values')){
  19.     $page_values = [];
  20.   }
  21.  
  22.   if ($form_state->getValue('next')) {
  23.     // Add the values to the page_value array.
  24.     foreach ($fields[$current_page] as $key) {
  25.       $page_values[$current_page][$key] = $form_state->getValue($key);
  26.     }
  27.     // Increment the page number.
  28.     $current_page++;
  29.   }
  30.   else if ($form_state->getValue('previous')) {
  31.     // Discard the values the page_value array.
  32.     foreach ($fields[$current_page] as $key) {
  33.       $form_state->setValue($key, $page_values[$current_page][$key]);
  34.       unset($page_values[$current_page][$key]);
  35.     }
  36.     // Decrement the page number.
  37.     $current_page--;
  38.   }
  39.  
  40.   $form_state
  41.     ->set('page_num', $current_page)
  42.     ->set('page_values', $page_values)
  43.     ->setRebuild(TRUE);
  44. }

Lastly, we add our custom validation function for the entire form. Notice we named the function user_register_pre_submit. This was done because we needed to alter the $form_state variables prior to the other validation functions getting run. Without this step, the fields that were on the previous pages would not be in the $form_state and would throw a validation error. This function puts all of the fields back into the existing $form_state, causing the validation functions to think it was a one page form submission again. Tricky!

  1. /**
  2.  * Custom function to re-add the form state values back from the page values.
  3.  *
  4.  * @param $form
  5.  * @param \Drupal\Core\Form\FormStateInterface $form_state
  6.  */
  7. function my_module_user_register_pre_submit($form, Drupal\Core\Form\FormStateInterface $form_state) {
  8.   // Load the submitted values.
  9.   $page_values = $form_state->get('page_values');
  10.   $submitted_values = $form_state->getValues();
  11.  
  12.   // Put all the paged values back into the form_state values.
  13.   foreach ($page_values as $page_num => $fields) {
  14.     foreach ($fields as $key => $value) {
  15.       $submitted_values[$key] = $value;
  16.     }
  17.   }
  18.  
  19.   // Save the form_state values for further processing.
  20.   $form_state->setValues($submitted_values);
  21. }

There you have it, a working two page registration form in Drupal 8. This could certainly be expanded to as many pages as necessary (but I only needed two).

Please let me know if you have any questions/comments.


Comments