This document provides instructions for creating a Drupal module that uses Ajax to dynamically populate a city select list based on the country selected. It involves creating the necessary module files like .info.yml and .routing.yml. It then builds a form with country and city select lists, and uses the #ajax property to call a callback function that returns the city options for the selected country. The form submission then saves the selected country and city to the database.
2. Topics
1. Create a custom form with Country and City Fields as select list and show data of cities when particular
country is selected using ajax change event.
3. Ajax Module Example
Step 1: Create .info.yml
Let's create a yml file. A yml file is a file that specifies the configuration for a file i.e., to store metadata information
about the project
name: Ajax Example
description: User Name or Email Ajax Validation
core: 8.x
type: module
4. Step 2: Creating .routing.yml Let’s create a .routing.yml called ajax_example.routing.yml. Each route is defined as a
machine name in the form of module_name.route_name
path: '/ajax_example'
defaults:
_form: 'Drupalajax_exampleFormAjaxExampleForm'
_title: 'Ajax Example'
requirements:
_permission: 'access content'
5. Step 3: Create AjaxExampleForm.php
Create a new file called AjaxExampleForm.php inside of src/Form/{AjaxExampleForm.php}.
getFormId() function is used to create a unique id to the form.
buildForm() function is used to create the form and it has a textfield to validate the username using #ajax. Drupal
provides the property ‘#ajax’ to a form element in your form array, to trigger an Ajax response.
6. <?php
/**
* @file
* Contains Drupalajax_exampleAjaxExampleForm
*/
namespace Drupalajax_exampleForm;
use DrupalCoreFormFormBase;
use DrupalCoreFormFormStateInterface;
use DrupalComponentUtilityUrlHelper;