You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Drupal 7:单页双表单通过AJAX回调实现下拉选值联动改字段

Hey there! Let's get that AJAX interaction between your two Drupal forms working. The core idea is to use the first form's selection to trigger an AJAX update that rebuilds the second form dynamically. Here's a step-by-step solution tailored to your code:

Solution: AJAX-Driven Dynamic Form Updates in Drupal

Step 1: Update the Main Form Structure

First, we'll wrap your second form in a container (so we can target it for AJAX replacement) and adjust the first form's AJAX settings to point to this container:

function my_form($form, &$form_state) {
  // First form select element
  $form['first_form'] = [
    '#title' => t('Choose:'),
    '#type' => 'select',
    '#options' => [
      '1' => 'First',
      '2' => 'Second',
      '3' => 'Third',
    ],
    '#required' => TRUE,
    '#ajax' => [
      'method' => 'replace',
      'callback' => 'my_form_state_ajax_callback',
      'wrapper' => 'second-form-container', // Target container for second form
      'event' => 'change', // Trigger on dropdown selection change
    ],
  ];

  // Container to hold the second form (for AJAX replacement)
  $form['second_form_container'] = [
    '#type' => 'container',
    '#attributes' => ['id' => 'second-form-container'], // Matches AJAX wrapper ID
  ];

  // Get the current selected value from form state (or empty if none)
  $selected_value = isset($form_state['values']['first_form']) ? $form_state['values']['first_form'] : '';
  
  // Build the second form dynamically based on the selection
  $form['second_form_container']['second_form'] = _build_dynamic_second_form($selected_value);

  return $form;
}

Step 2: Create the AJAX Callback Function

This function tells Drupal which part of the form to refresh. We'll rebuild the form state to ensure we have the latest selection, then return the updated second form container:

function my_form_state_ajax_callback($form, &$form_state) {
  // Rebuild the form state to preserve the latest selection
  $form_state['rebuild'] = TRUE;
  
  // Return the updated second form container to replace the old one
  return $form['second_form_container'];
}

Step 3: Build the Dynamic Second Form

Create a helper function that generates the second form's fields based on the first form's selected value. You can customize this to change field types, options, or visibility as needed:

function _build_dynamic_second_form($selected_value) {
  $second_form = [];

  // Customize fields based on the first form's selection
  switch ($selected_value) {
    case '1':
      $second_form['text_field'] = [
        '#title' => t('First Option Selected'),
        '#type' => 'textfield',
        '#description' => t('You picked the first option—enter some text here!'),
      ];
      break;
    case '2':
      $second_form['select_field'] = [
        '#title' => t('Second Option Selected'),
        '#type' => 'select',
        '#options' => [
          'a' => 'Sub-Option A',
          'b' => 'Sub-Option B',
        ],
        '#description' => t('Choose a sub-option from the dropdown.'),
      ];
      break;
    case '3':
      $second_form['textarea_field'] = [
        '#title' => t('Third Option Selected'),
        '#type' => 'textarea',
        '#description' => t('You selected the third option—write a longer message here.'),
      ];
      break;
    default:
      $second_form['default_message'] = [
        '#markup' => t('Please select an option from the first dropdown to see the second form.'),
      ];
  }

  return $second_form;
}

Key Things to Remember

  • Wrapper ID Match: The #wrapper value in the first form's AJAX settings must exactly match the id attribute of the second form's container. This is how Drupal knows which part of the page to update.
  • Form State Rebuild: Setting $form_state['rebuild'] = TRUE ensures the form retains the latest selection and rebuilds correctly after the AJAX call.
  • Flexibility: The _build_dynamic_second_form function lets you fully customize the second form—you can add/remove fields, change validation rules, or adjust labels based on the first form's input.

Testing the Setup

  1. Clear your Drupal cache (important since we added new functions).
  2. Load the form page and select an option from the first dropdown.
  3. The second form should update instantly without a full page reload.

内容的提问来源于stack exchange,提问作者T. Maxx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:00:56