Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form submit handlers with additional arguments

For some requirement I need to pass additional information to form submit handler. In form api, while defining custom submit handler as

$additional_args = array();
$form['#submit'][] = 'my_submit_handler'

I expect to submit handler as

function my_submit_handler($form, &$form_state, $additional_args){
like image 512
Shoaib Nawaz Avatar asked Aug 13 '10 07:08

Shoaib Nawaz


3 Answers

The submit handler is called by the drupal fapi, so you can't do something like that. Instead what you can do, is to add what you need, either to the $form, or to the $form_state. The usual approaches is to:

  • Added a field to the form, type value to store the value. Don't do this if you have the value in the form definition.

    $form['store'] = array(
      '#type' => 'value',
      '#value' => $value
    );
    

    This will be available in $form_state['values']['store'].

  • Add the value to $form_state['storage'], done if you variables in your validation handle you want to transfer to your submit handler:

    // Validation.
    $form_state['storage']['value'] = $value;
    
    ...
    
    // Submit
    $value = $form_state['storage']['value'];
    // Need to unset stored values when not used anymore.
    unset($form_state['storage']['value']);
    
like image 94
googletorp Avatar answered Oct 26 '22 18:10

googletorp


Drupal 7: Custom arguments are automatically propagated troug $form_state['build_info']['args'] This is said in http://api.drupal.org/api/drupal/includes!form.inc/function/drupal_get_form/7

Ex:

hook_form($form, &$form_state, $myAdditionnalArg) {...}

Then in

hook_form_submit($form, &$form_state) {

... //$form_state['build_info']['args'] is an array containing at index 0 the value of argument $myAdditionnalArg ...

like image 25
gipein Avatar answered Oct 26 '22 17:10

gipein


As reported in $form['#submit'] and $form['#validate'] and $form['#process'] no longer support custom parameters, the suggested way to pass parameters to a submission handler set as in the shown code is to use code similar to the following:

$form['#first_paramater'] = $value;
$form['#submit'][] = 'my_submit_handler';

The handler would retrieve the value as $form['#first_paramater']. To notice that, instead of #first_paramater, the code can use a different string, but it must start with #.

Normally it's not necessary to set a submission handler like the code does, but there are some cases where it is necessary, like to alter a form created by another module, or to set a different submission handler for each of the submission buttons present in a form.

drupal_retrieve_form() saves the parameters passed to the form build handler in $form['#parameters'] which contains:

  • $form_id
  • $form_state
  • parameters passed to the form builder
like image 4
apaderno Avatar answered Oct 26 '22 18:10

apaderno