drupal_prepare_form 大致是如何工作的 ?

函数原型是这样的

function drupal_prepare_form($form_id, &$form, &$form_state) {
//---
}

1 初始化一些变量

  $form['#type'] = 'form';
  $form_state['programmed'] = isset($form_state['programmed']) ? $form_state['programmed'] : FALSE;
        // Fix the form method, if it is 'get' in $form_state, but not in $form.
  if ($form_state['method'] == 'get' && !isset($form['#method'])) {
    $form['#method'] = 'get';
  }

2  form build id

  if (!isset($form['#build_id'])) {
    $form['#build_id'] = 'form-' . drupal_random_key();
  }
  $form['form_build_id'] = array(
    '#type' => 'hidden',
    '#value' => $form['#build_id'],
    '#id' => $form['#build_id'],
    '#name' => 'form_build_id',
    // Form processing and validation requires this value, so ensure the
    // submitted form value appears literally, regardless of custom #tree
    // and #parents being set elsewhere.
    '#parents' => array('form_build_id'),
  );

3 form token

$form['form_token'] = array(
        '#id' => drupal_html_id('edit-' . $form_id . '-form-token'),
        '#type' => 'token',
        '#default_value' => drupal_get_token($form['#token']),
        // Form processing and validation requires this value, so ensure the
        // submitted form value appears literally, regardless of custom #tree
        // and #parents being set elsewhere.
        '#parents' => array('form_token'),
      );

4 form id

  if (isset($form_id)) {
    $form['form_id'] = array(
      '#type' => 'hidden',
      '#value' => $form_id,
      '#id' => drupal_html_id("edit-$form_id"),
      // Form processing and validation requires this value, so ensure the
      // submitted form value appears literally, regardless of custom #tree
      // and #parents being set elsewhere.
      '#parents' => array('form_id'),
    );
  }

5 form['#id']

 if (!isset($form['#id'])) {
    $form['#id'] = drupal_html_id($form_id);
  }

6 action  + method   +  theme-wrapper

$form += element_info('form');

7 tree parents

$form += element_info('form');

8 validate | submit

 if (function_exists($form_id . '_validate')) {
      $form['#validate'][] = $form_id . '_validate';
    }

9 $form['#theme']

if (!isset($form['#theme'])) {
    $form['#theme'] = array($form_id);
    if (isset($form_state['build_info']['base_form_id'])) {
      $form['#theme'][] = $form_state['build_info']['base_form_id'];
    }
  }

10 为hook_form_alter做准备

  $hooks[] = 'form_' . $form_id;
  drupal_alter($hooks, $form, $form_state, $form_id);
原文地址:https://www.cnblogs.com/qinqiu/p/4494237.html