Drupal custom forms with Ajax dependent dropdowns
Creating a Drupal custom form with Ajax-based dependent dropdowns lets an editor make one choice and immediately receive only the relevant options for the next field. Selecting New South Wales could expose Sydney, Newcastle and Wollongong without reloading the page. The technique combines Drupal’s Form API, Ajax callbacks and a small amount of PHP; custom JavaScript is not required.
Keeping the filtering on the server is important when locations, product categories or service regions come from a content type, taxonomy or database table. The same pattern can power region, category and suburb selectors. It supports Drupal 10 and 11, works with native select elements, and suits both administrative workflows and public forms used by Australian customers.
| Pattern | Server-side filtering | Browser behaviour | Typical use |
|---|---|---|---|
| Form API with Ajax | PHP callback returns replacement HTML | Updates a dependent select | Custom validated forms |
| Entity autocomplete | Entity query supplies suggestions | Search and tagging interface | Large related datasets |
| JavaScript and JSON endpoint | API filters and returns data | Custom client-side logic | Sites with an existing public API |
| Contributed module | Module supplies its own callbacks | Depends on the module | Standardised editorial requirements |
Map the dependency before writing code
Start by naming the parent and child fields. Here, “State or territory” controls “City”. Each state uses a stable abbreviation as its option value, while the city options are filtered from that value. A dependent select should also have a clear empty option, because “no selection” is different from a city with the same name appearing under several states.
Decide where the options come from before building the interface. A small fixed dataset can live in a form class or service, but production data usually belongs in content, a taxonomy vocabulary or a dedicated repository. If a state can produce hundreds of locations, an autocomplete control may be easier to use than a long select element. The Ajax technique remains the same, while the child control changes.
Create the module and expose the form
Place the module in modules/custom/location_picker and enable it as usual. The information file declares compatibility with both supported major versions used by many Australian organisations during a Drupal upgrade cycle.
# location_picker.info.yml
name: 'Location picker'
type: module
description: 'Provides an Ajax-enabled dependent location form.'
core_version_requirement: '^10 || ^11'
The routing file makes the form available to authorised users. The permission can remain restricted to site administrators or be replaced with a custom editor permission. Public customer forms should have their own carefully tested access rules.
# location_picker.routing.yml
location_picker.form:
path: '/admin/content/location-picker'
defaults:
_form: '\Drupal\location_picker\Form\LocationPickerForm'
_title: 'Location picker'
requirements:
_permission: 'administer site configuration'
The form class belongs in src/Form/LocationPickerForm.php. Extending FormBase provides the form identifier and standard Drupal services without requiring a separate controller.
namespace Drupal\location_picker\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class LocationPickerForm extends FormBase {
public function getFormId(): string {
return 'location_picker_form';
}
Build the state select and city wrapper
buildForm() creates the parent select and the container that Drupal will replace after an Ajax request. The wrapper value must match the container’s HTML id. Using a native select preserves familiar behaviour for touch devices, keyboard users and screen readers.
public function buildForm(array $form, FormStateInterface $form_state) {
$location = $form_state->getValue('location') ?: [];
$state = (string) ($location['state'] ?? '');
$form['location'] = [
'#type' => 'details',
'#title' => $this->t('Location'),
'#open' => TRUE,
];
$form['location']['state'] = [
'#type' => 'select',
'#title' => $this->t('State or territory'),
'#options' => $this->stateOptions(),
'#empty_option' => $this->t('- Select a state or territory -'),
'#required' => TRUE,
'#ajax' => [
'callback' => '::ajaxUpdateCity',
'wrapper' => 'city-field-wrapper',
'event' => 'change',
],
];
$form['location']['city_wrapper'] = [
'#type' => 'container',
'#attributes' => ['id' => 'city-field-wrapper'],
];
$form['location']['city_wrapper']['city'] = [
'#type' => 'select',
'#title' => $this->t('City'),
'#options' => $this->cityOptions($state),
'#empty_option' => $this->t('- Select a city -'),
'#required' => TRUE,
];
return $form;
}
The example data covers all eight states and territories. The city names reflect common service areas in Sydney, Melbourne, Brisbane, Perth, Adelaide, Canberra, Hobart and Darwin rather than attempting to reproduce every Australian postcode.
protected function stateOptions(): array {
return [
'ACT' => 'Australian Capital Territory',
'NSW' => 'New South Wales',
'NT' => 'Northern Territory',
'QLD' => 'Queensland',
'SA' => 'South Australia',
'TAS' => 'Tasmania',
'VIC' => 'Victoria',
'WA' => 'Western Australia',
];
}
protected function cityOptions(string $state): array {
$cities = [
'ACT' => ['Canberra' => 'Canberra'],
'NSW' => [
'Sydney' => 'Sydney',
'Newcastle' => 'Newcastle',
'Wollongong' => 'Wollongong',
],
'NT' => [
'Darwin' => 'Darwin',
'Alice Springs' => 'Alice Springs',
],
'QLD' => [
'Brisbane' => 'Brisbane',
'Gold Coast' => 'Gold Coast',
'Cairns' => 'Cairns',
'Townsville' => 'Townsville',
],
'SA' => [
'Adelaide' => 'Adelaide',
'Mount Gambier' => 'Mount Gambier',
],
'TAS' => [
'Hobart' => 'Hobart',
'Launceston' => 'Launceston',
],
'VIC' => [
'Melbourne' => 'Melbourne',
'Geelong' => 'Geelong',
'Ballarat' => 'Ballarat',
],
'WA' => [
'Perth' => 'Perth',
'Albany' => 'Albany',
'Broome' => 'Broome',
],
];
return $cities[$state] ?? [];
}
Associative city options let the submitted value remain the city name while displaying a readable label. In a larger implementation, replace these methods with a service that queries a location table or Drupal entities.
Populate cities through an Ajax callback
The callback receives the rebuilt form and the form state. The triggering element identifies which control caused the request, allowing one callback to work with several dependent fields if necessary. It then returns the replacement wrapper, which Drupal inserts without reloading the page.
public function ajaxUpdateCity(
array &$form,
FormStateInterface $form_state
): array {
$trigger = $form_state->getTriggeringElement();
$state = (string) ($trigger['#value'] ?? '');
$form['location']['city_wrapper']['city']['#options'] =
$this->cityOptions($state);
$form['location']['city_wrapper']['city']['#value'] = '';
$form_state->setValueForElement(
$form['location']['city_wrapper']['city'],
''
);
return $form['location']['city_wrapper'];
}
Clearing the previous city prevents a value such as Brisbane from surviving when the editor changes the state to Western Australia. The browser receives the new select with an empty selection, and the next submission contains only a valid city for the current parent.
A third level can use the same design: a city select receives its own Ajax callback and replaces a suburb wrapper. Each callback should query only permitted choices and return the exact wrapper named in its parent’s #ajax configuration. Drupal’s core Ajax JavaScript handles the request and replacement, so a separate $.ajax() call is unnecessary.
Validate the selection and protect the workflow
Client-side filtering improves the interface, but it does not establish that the submitted relationship is valid. The form must independently confirm that the city belongs to the chosen state. This protects against stale fields, edited requests and clients that bypass the normal browser interaction.
public function validateForm(
array &$form,
FormStateInterface $form_state
): void {
$location = $form_state->getValue('location') ?: [];
$state = (string) ($location['state'] ?? '');
$city = (string) ($location['city_wrapper']['city'] ?? '');
$valid_states = array_keys($this->stateOptions());
if ($state !== '' && !in_array($state, $valid_states, TRUE)) {
$form_state->setErrorByName(
$form['location']['state']['#name'],
$this->t('Choose a valid state or territory.')
);
}
$cities = $this->cityOptions($state);
if ($city !== '' && !isset($cities[$city])) {
$form_state->setErrorByName(
$form['location']['city_wrapper']['city']['#name'],
$this->t('Choose a city available in the selected state.')
);
}
}
public function submitForm(
array &$form,
FormStateInterface $form_state
): void {
$location = $form_state->getValue('location');
$state = $location['state'];
$city = $location['city_wrapper']['city'];
$this->messenger()->addStatus($this->t('Saved @city, @state.', [
'@city' => $city,
'@state' => $state,
]));
$form_state->setRedirect('location_picker.form');
}
Drupal escapes option labels and form output, while its form token helps prevent cross-site request forgery. Database queries must still use parameterised conditions, and Ajax callbacks must never expose records that the current user is not permitted to see.
Accessibility also depends on more than the select elements. Ensure the changed options are announced through an appropriate status region, keep the field labels visible, and do not rely on colour to indicate the selection. Public-sector services commonly assess Drupal interfaces against the Australian Government Digital Service Standard and WCAG 2.2 AA.
Test the cascade under Australian conditions
Test every state and territory, including transitions that should invalidate the previous city. ACT to Canberra and WA to Perth should work, as should changing Queensland to New South Wales without Brisbane remaining selected. Also check slow connections, repeated changes, browser autofill, keyboard operation and the message received by a screen reader.
Many Australian checkout and service forms expect a suburb and four-digit postcode as well as a state. Postcodes are state-specific, so they can form another dependent field or provide a more precise location than a city alone. If the form schedules appointments, store identifiers such as Australia/Sydney or Australia/Brisbane; daylight-saving changes in Sydney and Melbourne make fixed UTC offsets unreliable.
When the form collects personal information and the organisation falls within the Privacy Act 1988, follow the Australian Privacy Principles, including purpose limitation, security, access and disposal. If a commercial electronic message is triggered by the selection, the Spam Act 2003 may require consent and sender identification. Cache dependent options only with the parent value in the cache key, and monitor Ajax responses for timeouts or failing data sources. The completed cascade then combines fast dependent choices with server-side validation and Drupal’s established security model.