How to keep data when using Drupal’s Form API – use storage

How to keep data when using Drupal’s Form API – use storage

So you created a form using the Drupal’s Form API. ¬†Great!

What if you want to access data in hook_validate or hook_submit without posting it in the form?  Storage is the answer.

function mymodule_test_form($form, &$form_state) {
  $form = array();
  $form['name'] = array(
    '#type' => 'text',
    '#title' => 'Your Name',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  $form_state['storage']['some_name'] = 'keep this';
  return $form;
}

function mymodule_test_form_submit($form, &$form_state) {
  $my_stored_value = $form_state['storage']['some_name']; // = 'keep this'
}

It’s that simple! You can store strings, arrays, objects, etc in there. Very useful if you want data to persist when the form is validated and/or submitted.

No Comments Yet.

Leave a comment