How to create dynamically populated cascading dropdown-lists for Contact Form 7

Something I had to deal with quite often lately, is creating dynamic drop-down lists in WordPress, like this:

As always, I like to use the WordPress plugin Contact Form 7 as a basis for all my form-driven projects. The reason is that Contact Form 7 has a robust validation mechanism. It is very lightweight, yet powerful and easy to use for both intermediate and advanced users. And lastly, because there is a great many plugins that build on top of CF7. These plugins allow you to turn CF7 in exactly the solution you need for your project. Nothing more, nothing less. But enough praising CF7, let’s build a form already!

The first thing you will need to do is get your data-set. For this example I will use a CSV file that is structured like this:

Let’s save this file as make-model-year.csv to our /wp-content/uploads/ folder.

Server side script

Now, let’s write our server side function, that will be called trough AJAX. You can add this function at the bottom of your theme’s functions.php file:

Server side script (PHP). Add this to functions.php

Don’t worry, if this does not make much sense to you yet. The function by itself will not do much, except read the CVS data, and returning it to the client side script (JavaScript).

The client side script

You should add this after the form is loaded. Typically you would create a custom page-template where you would include the form, or you could use an action hook to output the script, or add it to a seperate .js file. But for simplicity’s sake, we’ll just add it to footer.php, right before the </body> tag. So without further ado, here’s the script.

Client side script (JavaScript). Add this to footer.php

The Form

And the contact form 7 form itself? Simple! just add 3 select boxes with the names “makes”, “models” and “years”.

[select makes]
[select models]
[select years]