Saving Form Selection using Form API

During custom form submission we would want to remember the previous selection. There are many ways to do that, which includes using Sessions and variable_set to set the default value but this is an overkill if you wanted to simply preserve/remember the selection in the next page or after submission. The best way is to use $form_state['storage'] in your submit handler to hoard values between steps.

Consider an example:

<?php
function custom_form_submit($form, &$form_state) {
   
$start_date = $form_state['values']['startdate'];
   
$end_date =   $form_state['values']['enddate'];
   
$batch =   $form_state['values']['batch'];
   
// Store values
   
$form_state['storage']['update_startdate'] = $form_state['values']['startdate'];
   
$form_state['storage']['update_enddate'] = $form_state['values']['enddate'];
   
$form_state['storage']['update_batch'] = $form_state['values']['batch'];
   
// Rebuild the form
   
$form_state['rebuild'] = TRUE;   
   
//  Do other tasks
}
?>

After form rebuild the form would be changed to:

<?php
function custom_form(&$form_state) {
   
$form = array();
   
$form['startdate'] = array(
     
'#type' => 'date_popup',
     
'#title' => 'Start Date',
     
'#date_format' => 'Y-m-d',
     
'#date_label_position' => 'inline',
     
'#required' => TRUE,
     
'#tree' => TRUE,
    );

   
//This gets automatically added in form after rebuild
   
if (isset($form_state['storage']['update_startdate'])) {
     
$form['startdate']['#default_value'] = $form_state['storage']['update_startdate'];
    }
   
//... Additional form elements
   
return $form;
}
--
Source: <a href="http://stackoverflow.com/questions/1077806/drupal-formwant-to-show-previous-form-value-as-default-value-on-page
?>

">http://stackoverflow.com/questions/1077806/drupal-formwant-to-show-previ...