Drupal 6 Multi Step Form Creation

Code Snippet


November 7
blog author


Drupal 6 Multi Step Form Creation

Multiple step forms provide a more flexible approach for users. Read more about it on this blog!

The key things to make a form multiple pages are setting $form_state[‘rebuild’] and $form_state[‘storage’] variables in a submit function. 

function example_form_submit($form, &$form_state) {
  if($form_state['storage']['page'] == 1) {
    $form_state[‘rebuild’] = TRUE;
    $form_state[‘storage’][$page][‘values’] = $form_state[‘values’];
  else {
     //process the data

In Drupal 6 FormAPI, a form is cached after it is built once, so setting $form_state[‘rebuld’] to TRUE rebuilds the form from scratch and allows you to make changes on the form structure after the form is submitted. Also, storing the input from the form into $form_state[‘storage’] cache the data and carries them to the next page so you can process all inputs together when the last step form is submitted.

This is a very simple multi-step form which asks users to choose a type of contents on the first page and provides different input fields based on user’s choice from the first step on the next page. The form function was like:

function example_form(&$form_state) {
  if(isset($form_state['storage']['page'])) {
    $page = $form_state[‘storage’][‘page’];
  } else {
    $page = 1; 
  switch($page) {
    case 1:
      $form['content_types'] = array(
        '#type' => 'radios',
        '#title' => t('Content Type'),
        '#description' => t('Select a content type'),
        '#options' => $options );
    case 2:
        $type = $form_state['values']['content_types'];
        $form['content_fields'] = example_content_fields_form($type);
    return $form;


When the form is loaded first time, $form[‘storage’][‘page’] is not set yet. Set this ‘page’ key to 1 as a default value. Now you can create form elements based on the value of this ‘page’ variable. When the form is submitted, the submit function stores the input data to $form_state[‘storage’] variable and increments the page counter. Drupal FAPI reloads the form and back to the form function again.

You can create a form with more steps in the same way applying more page counts. Also, this works with hook_form_alter() so you can customize Drupal forms such as a registration form.