Drupal Form:want to show previous form value as default_value on page

14,370

Solution 1

You can use $form_state['storage'] in your submit handler to hoard values between steps. So add a submit function like so:

function addnewproduct_form_submit ($form, &$form_state) {
  // Store values
  $form_state['storage']['addnewproduct_productname'] = $form_state['values']['productname'];
  // Rebuild the form
  $form_state['rebuild'] = TRUE;    
}

Then your form builder function would become:

function addnewproduct_form(&$form_state) { 

$form = array();

$form['productname'] = array (
'#type' => 'textfield',
'#title' => t('Product Name'),
'#required' => TRUE,
'#size' => '20',

);

if (isset($form_state['storage']['addnewproduct_productname'])) {
  $form['productname']['#default_value'] = $form_state['storage']['addnewproduct_productname'];
}

return $form;
}

Just remember that your form will keep being generated as long as your $form_state['storage'] is stuffed. So you will need to adjust your submit handler and unset($form_state['storage']) when are ready to save values to the database etc.

If your form is more like a filter ie. used for displaying rather than storing info, then you can get away with just

function addnewproduct_form_submit ($form, &$form_state) {
  // Rebuild the form
  $form_state['rebuild'] = TRUE;    
}

When the form rebuilds it will have access to $form_state['values'] from the previous iteration.

Solution 2

Drupal will do this by default if you include:

$formproductname['#redirect'] = FALSE;

In your $formproductname array.

Share:
14,370
Admin
Author by

Admin

Updated on June 30, 2022

Comments

  • Admin
    Admin almost 2 years

    My Goal is if user is submitting this form with "Product Name" value as "YYY". On submit page should reload but this time "Product Name" should show previous valye as default as in this case "YYY".

    Here is my code...

    function addnewproduct_page () {
      return drupal_get_form('addnewproduct_form',&$form_state);
    }
    
    function addnewproduct_form(&$form_state) {
      $form = array();
    
    
        $formproductname['productname'] = array (
        '#type' => 'textfield',
        '#title' => t('Product Name'),
        '#required' => TRUE,
            '#size' => '20',
      );
    
        if (isset($form_state['values']['productname'])) 
        {
        $form['productname']['#default_value'] = $form_state['values']['productname'];
      }
    
      //a "submit" button
      $form['submit'] = array (
        '#type' => 'submit',
        '#value' => t('Add new Product'),  
      );
      return $form;
    }
    
  • Fedir RYKHTIK
    Fedir RYKHTIK almost 13 years
    It's too much GLOBAL solution, overkilling
  • FLY
    FLY over 11 years
    great answer I've been looking for this for days! +1