Created
April 20, 2014 06:29
-
-
Save drmalex07/11106713 to your computer and use it in GitHub Desktop.
An example with multistep forms in drupal7. #drupal #drupal7 #multistep-form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function helloworld_multistep_example_form($form, &$form_state) | |
{ | |
// We add 2 keys to form_state ("step" and "state") to keep track | |
// of state in a multistep form. | |
$step = isset($form_state['step'])? ($form_state['step']) : (1); | |
$form['heading'] = array( | |
'#type' => 'markup', | |
'#markup' => "<h3>Step #${step}</h3>" | |
); | |
switch ($step) { | |
case 2: | |
{ | |
// Render form elements for step #2 | |
$qty = $form_state['state']['order_qty']; /* retreive value from step #1 */ | |
$form['order_qty_item'] = array('#type' => 'item', '#markup' => "${qty} foobars", '#title' => 'Order Quantity'); | |
$form['deliver_address'] = array('#type' => 'textfield', '#size' => 30, '#title' => 'Address'); | |
$form['submit'] = array('#type' => 'submit', '#value' => 'Submit'); | |
} | |
break; | |
case 1: | |
default: | |
{ | |
// Render form elements for step #1 | |
$form['order_qty'] = array('#type' => 'textfield', '#size' => 5, '#title' => 'Order Quantity'); | |
$form['next'] = array('#type' => 'submit', '#value' => 'Next'); | |
} | |
break; | |
} | |
return $form; | |
} | |
function helloworld_multistep_example_form_submit($form, &$form_state) | |
{ | |
$step = isset($form_state['step'])? ($form_state['step']) : (1); | |
$values =& $form_state['values']; | |
switch ($step) { | |
case 2: | |
{ | |
// This was the final step: use values from all previous steps ... | |
$qty = $form_state['state']['order_qty']; /* from step #1 */ | |
$address = $values['deliver_address']; /* from step #2 - (current step) */ | |
drupal_set_message("You are about to receive ${qty} foobars at address ${address}"); | |
} | |
break; | |
case 1: | |
default: | |
{ | |
// Prepare for next step | |
$form_state['step'] = 2; | |
$form_state['state'] = array('order_qty' => $values['order_qty']); | |
$form_state['rebuild'] = true; /* required in order to rebuild form in each step!! */ | |
} | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was very useful. First step data is lost in the second step, any clean way to carry it ?