Drupal Form API and $ form_state ['storage'] are destroyed when the page is refreshed

I have a form that displays two submit buttons. The first submit button sets the $ form_state ['storage'] value. The second submit button then reads this value of $ form_state ['storage']. If set, a success message is displayed. If not set, an error message is displayed.

Here is the code that will reproduce my problem:

function mymodule_test_admin() { return drupal_get_form('mymodule_test_form'); } function mymodule_test_form(&$form_state) { $form['mymodule_test_form1'] = array( '#type' => 'fieldset', '#title' => t('test 1'), '#collapsible' => TRUE, '#collapsed' => FALSE, '#tree' => TRUE ); $form['mymodule_test_form1']['submit'] = array( '#type' => 'submit', '#value' => t('button 1'), '#submit' => array('mymodule_test_form1_submit') ); $form['mymodule_test_form2'] = array( '#type' => 'fieldset', '#title' => t('test 2'), '#collapsible' => TRUE, '#collapsed' => FALSE, '#tree' => TRUE ); $form['mymodule_test_form2']['submit'] = array( '#type' => 'submit', '#value' => t('button 2'), '#submit' => array('mymodule_test_form2_submit') ); return $form; } function mymodule_test_form1_submit($form, &$form_state) { $form_state['storage']['test_1'] = 'test 1'; drupal_set_message(t('@message', array('@message' => $form_state['storage']['test_1']))); } function mymodule_test_form2_submit($form, &$form_state) { if (isset($form_state['storage']['test_1'])) { drupal_set_message(t('success')); } else { drupal_set_message(t('fail!')); } } 

When you press the first submit button, $ form_state ['storage'] is set correctly. When you press the second submit button, the message "success" is displayed. So far, so good. Now refresh the page. The message "fail!".

So, everything works right up to the page refresh. Refreshing the page essentially only calls the second submit function. Theoretically, the value of $ form_state ['storage'] should be filled, and the displayed message should be "successful." However, looking at the dump of $ form_state, $ form_state ['storage'] is NULL after refreshing the page. I can’t say if my code logic is wrong or if $ form_state ['storage'] is cleared when the page is refreshed.

Any ideas?

Thanks for your help.

+4
source share
2 answers

You will need to rebuild the form at the end of the 1_submit processing form, this will retain the old values. This is some kind of multi-stage form script, but a bit different than how it was done in Drupal 5.

 function mymoduel_test_form1_submit($form, &$form_state) { $form_state['storage']['test_1'] = 'test 1'; drupal_set_message(t('@message', array('@message' => $form_state['storage']['test_1']))); $form_state["rebuild"] = TRUE; } 

Hope this helps, Sarfaraz

+8
source

Storage after sending will be cleared, use $ _SESSION ['mymodule_test_XXX'] for storage in multi-stage forms ...

+1
source

Source: https://habr.com/ru/post/1302635/


All Articles