Last active
July 28, 2020 09:24
-
-
Save leepettijohn/0b1c392c179c5ca9869c459260ae7bad to your computer and use it in GitHub Desktop.
Gravity Forms - Dynamic Dropdown, Radio Button, Multi Select
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/*-----------------------------------------------------------------------------------*/ | |
/* Putting Locations in a Dropdown, Radio Button, or Multi-Select */ | |
/* Helpful article - https://www.gravityhelp.com/documentation/article/dynamically-populating-drop-down-fields/ */ | |
/*-----------------------------------------------------------------------------------*/ | |
$location_form_id = 9; | |
add_filter( 'gform_pre_render_'.$location_form_id, 'populate_posts' ); | |
add_filter( 'gform_pre_validation_'.$location_form_id, 'populate_posts' ); | |
add_filter( 'gform_pre_submission_'.$location_form_id, 'populate_posts' ); | |
add_filter( 'gform_pre_submission_filter_'.$location_form_id, 'populate_posts' ); | |
add_filter( 'gform_admin_pre_render_'.$location_form_id, 'populate_posts' ); | |
function populate_posts( $form ) { | |
foreach ( $form['fields'] as &$field ) { | |
if ( $field->label == 'Location') { | |
$posts = get_posts( 'post_type=location&orderby=title&order=ASC' ); | |
/* Other qualifiers on https://codex.wordpress.org/Template_Tags/get_posts */ | |
$choices = array(); | |
foreach ( $posts as $post ) { | |
$choices[] = array( 'text' => $post->post_title, 'value' => $post->post_title ); | |
} | |
// I added this line to add 'Other Post' in case you want a different value not listed. | |
// Then you can use conditional logic to show a field in the case this option is selected | |
$choices[] = array('text' => 'Other Post', 'value' => 'Other Post'); | |
// update 'Select a Post' to whatever you'd like the instructive option to be | |
$field->placeholder = 'Select a Post'; | |
$field->choices = $choices; | |
} | |
} | |
return $form; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment