#! code: Drupal 9: Cascading Ajax Select Forms

Tying together different select elements in a form is done with very little effort thanks to the ajax and states system built into Drupal 9. This means that any Drupal form can have a select element that shows and updates options into another select element within the same form. Using this system you can create a hierarchical system where one select will show and populate another select element with items dependent on the first. This is great for giving the user the ability to drill down into options that are dependent on each other. As the user selects the first select element the second select element will populate with data and be shown on the screen.

It does, however, require a few things to be in place first and so takes a little while to set up. There are also two different ways to set up this kind of system, both of which have their limitations. I found a lot of information out there on how to implement one system, but not the other. I thought I would create a post to show how each system can be set up and where it can be used.

The Form

Before jumping into the ajax components we need a form. The simplest, independent and most universally accepted set of select elements I could think of is a date picker. You wouldn’t normally display the date as a set of select elements (although I have seen this before), but the data behind it is simple enough to understand and doesn’t require any other aspects from Drupal to use.

Here is the form we will generate here.

Read more.