Skip to main content

Form Elements

Displaying 1 - 2 of 2

Select Element with AJAX updating form dynamically

Using AJAX callbacks to dynamically react on user input, alter form elements, show dialog boxes or run custom Javascript functions.

Ajax is the process of dynamically updating parts of a page's HTML based on data from the server without requiring full page refresh. You can find events triggering Ajax requests all over Drupal.

<?php
  namespace Drupal\drupalvip\Form;

  use Drupal\Core\Form\FormBase;
  use Drupal\Core\Form\FormStateInterface;
  
  class AjaxForm extends FormBase {    

    public function getFormId() {
      return 'mymodule_ajax_form';
    }

    public function buildForm(array $form, FormStateInterface $form_state) {
      $triggering_element = $form_state->getTriggeringElement();

      $form['country'] = [
        '#type' => 'select',
        '#title' => $this->t('Country'),
        '#options' => [
          'serbia' => $this->t('Serbia'),
          'usa' => $this->t('USA'),
          'italy' => $this->t('Italy'),
          'france' => $this->t('France'),
          'germany' => $this->t('Germany'),
        ],
        '#ajax' => [
          'callback' => [$this, 'reloadCity'],
          'event' => 'change',
          'wrapper' => 'city-field-wrapper',
        ],
      ];

      $form['city'] = [
        '#type' => 'select',
        '#title' => $this->t('City'),
        '#options' => [
          'belgrade' => $this->t('Belgrade'),
          'washington' => $this->t('Washington'),
          'rome' => $this->t('Rome'),
          'paris' => $this->t('Paris'),
          'berlin' => $this->t('Berlin'),
        ],
        '#prefix' => '<div id="city-field-wrapper">',
        '#suffix' => '</div>',
        '#value' => empty($triggering_element) ? 'belgrade' : $this->getCityForCountry($triggering_element['#value']),
      ];

      return $form;
    }

    public function reloadCity(array $form, FormStateInterface $form_state) {
      return $form['city'];
    }

    protected function getCityForCountry($country) {
      $map = [
        'serbia' => 'belgrade',
        'usa' => 'washington',
        'italy' => 'rome',
        'france' => 'paris',
        'germany' => 'berlin',
      ];
      return $map[$country] ?? NULL;
    }

    public function submitForm(array &$form, FormStateInterface $form_state) {  }

} // end of class