开发者

Form submit handlers with additional arguments

Fo开发者_如何学Cr 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){


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']);
    


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 ...


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜