I like building forms. So much so that I've even been teased about it. Despite that I want to share how multistep forms have changed for Drupal 7 and to expand on how you can use variable functions to achieve cleaner and easier form step logic, including easily moving backwards in forms. Understanding multistep in Drupal 7 was prompted by my need to create easy forms for an internal GVS project that will hopefully launch soon.
Multistep in Drupal 7
In Drupal 6 to carry data back to your form builder you set the storage
key of $form_state
in your submit handler. In Drupal 7, upon return to your builder after submission, you carry data over by keeping the Form API from pulling the form array out of cache*. You do so by setting $form_state['rebuild']
to TRUE
in your validate or submit handlers. Another change is the first argument of your builder must be $form
because of changes to drupal_get_form(). &$form_state
is now your second argument to your form builder.
Update: 'rebuild' existed in Drupal 6 (thanks Wim) but now seems to be required for multistep to work in Drupal 7.
Drupal 7:
<?php
// Form builder definition.
function my_form($form, &$form_state) {...}
// Form submit handler.
function my_form_builder_submit($form, &$form_state) {
// Trigger multistep.
$form_state['rebuild'] = TRUE;
// Store values that will be available when we return to the definition.
$form_state['storage']['values'] = $values;
}
?>
Let's look at a example:
<?php
// multistep_simple, our form builder function.
function multistep_simple($form, &$form_state) {
// Check if storage contains a value. A value is set only after the form is submitted and 'rebuild' is set to TRUE.
if (!empty($form_state['storage']['myvalue'])) {
// Display a message with the submitted value.