So recently someone asked me, "Can Gravity Forms pre-populate a dropdown [radio or select] with information based on a previous input in a multipage form?" While the options are plenty to make this happen with the very many Gravity Form hooks. Some include the following (but not limited to):
- Set a cookie & retrieve the cookie for use later using setcookie() & $_COOKIE.
- Use jQuery (and/or AJAX) to populate fields
While both of these are extremely viable options, what this person wanted was to search a custom post type for someone's name. So on page 1 of the form was an input for the person's name.
While logically, one would think that the gform_field_value_$parameter_name filter would work, I couldn't for the life of me determine how to do this for select and/or radio fields. So, I switched back to gform_pre_render hook. As you may or may not know gform_pre_render hook gives you the $form object to manipulate prior to rendering the form and executed before the form is displayed, which is what I needed.
Setup
In order to set this up, you will need two things:
- A custom post type called 'Persons' (wps_person), which served as the body of data that would pre-populate the radios.
- A simple Multipaged form
Gravity Forms Multi-paged Form
So create a new gravity form. Add a name (Field ID:1), then add a radio field. In the name field select either Normal (this is what the example uses) or Simple (example has a commented out replacement for this). Have the name on page 1 and the radio options on page 2. In the radio field, do the following under the Advanced Tab:
- Add a CSS class name 'person'
- Check "Allow field to be populated dynamically" but no need to choose a parameter name
Now you are ready...
Gravity Forms Customization
First, we have to cycle through the form fields. Gravity Forms does not prepped the Form Object (here $form) where the key is the Field ID (though that would be nice).
Next, in this snippet, you will notice a check at the beginning to see if we are on the correct field. You may think I go overboard, but I don't want to edit the wrong field. So I am checking for the following:
- Field Type
- CSS class
- Allows pre-population
[php]
if ( 'radio' != $field['type'] || false === strpos( $field['cssClass'], 'candle-person' ) || ! rgar( $field, 'allowsPrepopulate' ) )
[/php]
While you don't necessarily need all three per se, I find that I don't run into errors when I do all three.
Third, we do a new WP_Query() (see codex for more information & see Mark Luetke's (Github, Site) WP_Query Args Gist) searching for those items that match the name. Here I access the $_POST var with the appropriate input_*_* name. I then also tell it to query my post type ('wps_person'). For future possibilities, I add another query var 'gform_search', just in case I want to do something with pre_get_posts later, but that's for more advanced usage.
Then, I just cycle through the available posts to create my choices, and return the form.
Here's an example: