Implementing AJAX callbacks for dynamic formsfor Drupal 8 , 9 , 10 , and 11

Last updated :  

Building on the foundational skills of form processing and validation, this lesson delves into enhancing user interaction with AJAX callbacks in Drupal forms. AJAX allows for updating and responding to user input dynamically, creating a more interactive and efficient user experience.

Understanding AJAX in Drupal Forms

AJAX (Asynchronous JavaScript and XML) in Drupal forms enables elements to change dynamically without requiring a full page reload. By leveraging built-in AJAX features, you can create forms that respond quickly to user actions, improving usability and performance.

Why Use AJAX Callbacks?

Implementing AJAX in forms offers several advantages:

  • Improved User Experience: Provides a seamless and interactive experience by updating only parts of the page.
  • Enhanced Performance: Reduces server load and increases response times by limiting full-page refreshes.
  • Dynamic Interactions: Allows for real-time data validation and customization based on user input.

Example Scenario: Dynamic Weather Module Settings

Continuing with our weather module, we will create a form where users can select a country, and an AJAX callback automatically updates the list of available cities in a dropdown based on the selected country.

Step 1: Define the Dynamic Form Class

Create a new form in your module to implement AJAX interactions:


// weather_module/src/Form/WeatherAjaxForm.php

namespace Drupal\weather_module\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class WeatherAjaxForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'weather_ajax_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    // Country dropdown with AJAX callback triggers.
    $form['country'] = [
      '#type' => 'select',
      '#title' => $this->t('Select Country'),
      '#options' => ['us' => $this->t('United States'), 'ca' => $this->t('Canada')],
      '#ajax' => [
        'callback' => '::updateCityDropdown', 
        'event' => 'change', 
        'wrapper' => 'city-wrapper', 
      ],
    ];

    // City dropdown placed within an AJAX wrapper.
    $form['city'] = [
      '#type' => 'select',
      '#title' => $this->t('Select City'),
      '#prefix' => '
', '#suffix' => '
', '#options' => $this->getCityOptions($form_state->getValue('country', 'us')), ]; $form['submit'] = [ '#type' => 'submit', '#value' => $this->t('Submit'), ]; return $form; } /** * AJAX callback to refresh the city dropdown. */ public function updateCityDropdown(array &$form, FormStateInterface $form_state) { return $form['city']; } /** * Helper function to fetch city options based on selected country. */ protected function getCityOptions($country) { if ($country == 'us') { return ['nyc' => $this->t('New York City'), 'la' => $this->t('Los Angeles')]; } elseif ($country == 'ca') { return ['tor' => $this->t('Toronto'), 'van' => $this->t('Vancouver')]; } return []; } /** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $this->messenger()->addMessage($this->t('Form submitted! Country: @country, City: @city', [ '@country' => $form_state->getValue('country'), '@city' => $form_state->getValue('city'), ])); } }

Step 2: Configure the AJAX Callback

The '#ajax' property in the country dropdown specifies that an AJAX call should be triggered on change. The updateCityDropdown function redisplays the relevant part of the form—specifically, the city dropdown.

Step 3: Implement and Test the Form

Create a route pointing to this form and test it by changing the country dropdown. Observe how the city dropdown updates interactively without reloading the page.


// weather_module.routing.yml

weather_module.ajax_form:
  path: '/weather/ajax-form'
  defaults:
    _form: '\Drupal\weather_module\Form\WeatherAjaxForm'
    _title: 'Weather AJAX Form'
  requirements:
    _permission: 'access content'

Benefits of AJAX in Drupal Forms

Ajax integration in forms not only modernizes the user interface but also empowers developers to construct applications that can interact smoothly with users, providing dynamic and responsive input options.

Conclusion and Next Steps

In this lesson, you learned to implement AJAX callbacks in Drupal forms, enhancing interactivity and performance. This capability is essential for crafting engaging and efficient user interfaces.

Next, we’ll explore "Using hook_form_alter() to modify core or contrib forms", enabling you to customize existing forms dynamically according to your project’s unique needs.

Continue evolving your skills, and I'll guide you through the next phase of Drupal module development!