3

How to transfer the submitted data too when redirecting a form through $form_data['#redirect']?

Like :

hook_menu declares : page-1, page-2

page-1 having a form that when submitted triggers page_1_form_submit() (in which I does the redirection)

but I'd like that once redirected to page-2, page_2_page() (registered as render function in hook_menu) can access the previously submitted data!

:)

2 Answers 2

5

In the form submission of the first page you can copy the values in $form_state['values'] into the session for the current user; the page callback of the other page can then access them.

function mymodule_page1_form_submit($form, &$form_state){
  $_SESSION['mymodule_page1_submission_timestamp'] = time();
  $_SESSION['mymodule_page1_submitted_values'] = $form_state['values'];


  $form_state['redirect'] = 'The path for the second page';
}

function mymodule_page2_view() {
  $delay = 300;
  if (!empty($_SESSION['mymodule_page1_submitted_values']) && !empty($_SESSION['mymodule_page1_submission_timestamp'])) {
    $submitted_data = ($_SESSION['mymodule_page1_submission_timestamp'] > time() - $delay) ? $_SESSION['mymodule_page1_submitted_values'] : array();
    unset($_SESSION['mymodule_page1_submission_timestamp']);
    unset($_SESSION['mymodule_page1_submitted_values']);       
  }

  // ...
}

I use $_SESSION['mymodule_page1_submission_timestamp'] just to avoid the second page gets the values submitted on the form present in the first page more than 5 minutes before. If you don't want such restriction, then remove any reference to $delay.

You could also pass the values through the URL, but there is a restriction on the URL length the browsers can handle, and that restriction depends on the browser, as long as I know.

1
  • Excellent! Using $_SESSION and not to let the user alter the data is a good solution, I think. Thank you again! Nov 16, 2012 at 8:26
1

in your submit function , add your data in the redirect url.

function page_1_form_submit($form, &$form_state){
$data_a = $form_state['values']['data_a_form'];
$data_b = $form_state['values']['data_b_form'];

$options = array(
    'query' => array(
         'data_a' => $data_a,
         'data_b' => $data_b,
        )
    );

$form_state['redirect'] = array('url_page2', $options);
}

The redirection will be

 www.domaine.com/url_page2?data_a=XXX&data_b=YYYY;

In the page_2 form, gather datas from $_GET variable

$data_a = $_GET['data_a'];
$data_b = $_GET['data_b'];

Don't forget to check your datas, like is_numeric, etc ...

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.