Dynamically Populate Gravity Forms Drop Down Fields

Gravity Forms is one of the best form plugins for WordPress powered websites. It allows you to quickly and easily create a form by dragging and dropping form elements into the editor, change their names, properties and settings. One of many elements available to use is the drop down field. You can either add the values manually using the form editor or populate all items dynamically via filters in your code.

For this example we will be covering dynamic drop down population via filters. We’ll end up with a drop down field populated with a list of movies, which is set up as a custom post type in our WordPress installation.

The first thing we’re going to do is add a new drop down field to our form. Here is what it looks like when you expand the edit options:

Drop down field

In order to keep it organized, and since we’re going to dynamically populate the items, we can delete all the default items (First Choice, Second Choice, Third Choice) that Gravity Forms adds when you add the field to the form.

If you check the official Gravity Forms documentation, you will see that it suggests you to write down the Field Id (in this example, id = 5) so you can use it in your code to target the correct element to be populated.

Even though this will work, I would prefer to add a class to the element and check for this class when targeting the element in the code. This way there’s no need to worry about ids, which sometimes can be a problem if you work with different environments or servers where the ids can be different on each installation.

For this field, we’re going to use the class name ‘movies-dropdown’, set under Appearance > Custom CSS Class on our drop down.

Drop down settings

With our drop down set up in the form editor, it’s time to created the logic behind it. The filter we’ll be using is the ‘gform_pre_render’ filter, which is executed before the form is displayed and can be used to manipulate the Form Object prior to rendering the form.

Here is the code:

 

Gravity Forms is an great plugin and it allows you to build pretty much any custom functionality using its Hooks and Filters, and there are many others you can use. For more information and details about all of the Gravity Forms features, you can always refer to their official API Functions documentation.

Hope this helps and see you next time!