Posted on by

Pre-load a “Chosen” Dropdown with Options from the Database

The Chosen Dropdown add-on for Participants Database gives you the ability to use javascript-powered dropdown selectors in your forms. Normally, these dropdowns are populated with a static set of values in the field definition.

This tutorial shows how to populate your Chosen dropdown with values from the database.

For our tutorial here, we’re going to do something very simple: the field (named “Specialty”) is a Chosen Dropdown Other field where users can type in an additional value that is not on the preset list. What this does is make it possible for another person to select that new option in their form, giving you an essentially user-defined list of options for the dropdown.

Getting the Values

The core of this function (happens around line 30) is the database query that gets all the values that people have saved. If you are adapting something like this for your own purposes, you will need to be able to change this part of the function to get whatever list of options you want to use. This will require some knowledge of database queries, but WordPress makes this pretty simple.

To start with, we are simply going to query the database for all the unique values that have been saved. Then we add the ones that aren’t already present in the list of options to the preset values to get our final list of options.

Setting the Field’s New Options

Setting the field options is very simple, we simply need an array of values, then we set the “options” property of the field to that array. In this case, it’s a simple indexed array, so the saved value and what you see in the dropdown are exactly the same.

Participants Database also supports “value titles” where the visible part of the option can be different from the value that gets saved. You just need to construct your array as an associative array where the title is the key and the value is the value in each array element.

Here’s the Code

I tried to make the plugin code simple and well-commented so it’s easy to understand what is going on here.

As always, go to the gist page and download the zip file if you want to install this plugin.

Leave a Reply
You have to agree to the comment policy.

Leave a Reply
You have to agree to the comment policy.