drupaldrupal-fapi

passing information from a Drupal Forms API validation function to a submit function


In my validation function for a Drupal Forms API form, I attempt to charge the user's credit card. If it succeeds, I'd like to pass the reference number to the submit function so it can be used there. What's the best way of doing this?


Solution

  • The documentation says this:

    Note that as of Drupal 6, you can also simply store arbitrary variables in $form['#foo'] instead, as long as '#foo' does not conflict with any other internal property of the Form API.

    So you could do something like this:

    function form($form_state) {
    //in your form definition function:
    $form['#reference_number'] = 0;
    }
    
    function form_validate($form, &$form_state) {
      //try to charge card ...
      if ($card_charged) {
        $form_state['values']['#reference_number'] = $reference_number;
      }
    }
    
    function submit_form($form, &$form_state) {
      if (isset($form_state['values']['#reference_number'])) {
        $reference_number = $form_state['values']['#reference_number'];
        //do whatever you want
      }
    }