[Drupal] How to retain the default values of step 1 form after successfully submitting the step 2 form of a two step form

| | 2 min read

To keep the default values of the step one form after successfully submitting the step 2 form, here is an easy way. Just pass the form state values of step 1 form as query parameters to the same page on submitting step 2 form. Set the default values of step 1 form as, first check whether the form_state value is set. If yes, set the default values of step 1 form fields with the form_state values. Else check the URL query parameters, whether this variable is set. If yes, then set the default value with that value.

As the simple multi step form example tutorial in the examples module, if you have a field like first name in the step 1 form, then its default value could be set as follows.

$parameters = drupal_get_query_parameters();
$form['first'] = array(
  '#type' => 'textfield',
  '#title' => t('First name'),
  '#description' => "Please enter your first name.",
  '#size' => 20,
  '#maxlength' => 20,
  '#required' => TRUE,
);
if (isset($form_state['values']['first'])) {
  $form['first']['#default_value'] = $form_state['values']['first'];
}
elseif (isset($parameters['first'])) {
  $form['first']['#default_value'] = $parameters['first'];
}

In the submit function of the step two form, redirect the user to the current page by setting the form_state step 1 values as query parameters.

$parameters = array();
if (!empty($form_state['page_values'][1])) {
  // Slice the $form_state['page_values'][1] array to get the form_state values of only the input fields of the step 1 form.
  $parameters = array_slice($form_state['page_values'][1], 0, 3);
  $path = current_path();
  drupal_goto($path, array('query' => $parameters));
}

The above code is really easy and will be helpful. Please feel free to get in touch with us if you have any queries regarding the same.