Archive for July, 2008

How to Create Multistep Form in Drupal 6 – Tutorial

Saturday, July 26th, 2008

CMS system will help us to quickly have the base system but it will limit our development if we are not familiar with the API. Multistep form is a form which has multiple pages of fields and the user should go through each page until at the end of the step. I will touch on how to turn Drupal 6 form into multistep/flowing form.

If you come across Drupal Form API you will realize that by default, the form is declared as associative arrays which are displayed in one page.
$form[‘field_id’] = array (
‘#type’ => ‘textfield’,
‘#title’ => t(‘The label of the input field’),
‘#size’ => 40,
‘#description’ => t(‘Description of the field which appear below input box’),
‘#required’ => TRUE);
);

For complete reference on Drupal 6 Form API visit this site:  http://api.drupal.org/api/file/developer/topics/forms_api_reference.html/6

The key to get multistep behavior of the form is by putting $form_state[‘rebuild’] = true; statement inside your form submit function. This statement will call again the function which renders the form when the user clicks submit. By manipulating form function to return different associative arrays we can get multistep form behavior.

The second important step is to store the form state values as we keep redrawing the form so that we do not lost the inputted values from previous step. We can do this inside form submit function and store the value in $form_state[‘storage’] since this is session based variable. $form_state[‘storage’][‘values’] = $form_state[‘values’]; Below is the snippet code example for multistep form in Drupal 6:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function mymodule_myform($form_state) {
   if (empty($form_state['storage']['values'])) {
      $form['firstname'] = array(
         '#type' => 'textfield',
         '#title' => t('First Name'),
         '#size' => 40,
         '#required' => TRUE
      );
   } else {
      $form['lastname'] = array(
         '#type' => 'textfield',
         '#title' => t('Last Name'),
         '#size' => 40,
         '#required' => TRUE
      );
   }
}
Function mymodule_myform_submit($form, &$form_state) {
   if (empty($form_state['storage']['values'])) {
      // if there is no previous values redraw for second step
      $form_state['storage']['values'] = $form_state['values'];
      $form_state['rebuild'] = true;
   } else {
      // Form is on the second step, process the data here…
      $firstname = $form_state['storage']['values'][‘firstname’];
      $firstname = $form_state['storage']['values'][‘lastname’];.
   }
}

Above example will create two steps form, to create more steps you can create $form_state[‘storage’][‘step’] which will be assigned with the current step number. You could also use form alter hook mymodule_form_alter(&$form, $form_state, $form_id) to modify existing form.