December 28, 2016
Gravity Forms is a powerful plugin!
Using this function, display values in the select dropdown field dynamically, based on parameters you set in the foreach loop.
Default Code from Gravityhelp.com
- pre_render populates the field by form number
add_filter( 'gform_pre_render_51', 'populate_posts' );
add_filter( 'gform_pre_validation_51', 'populate_posts' );
add_filter( 'gform_pre_submission_filter_51', 'populate_posts' );
add_filter( 'gform_admin_pre_render_51', 'populate_posts' );
function populate_posts( $form ) {
foreach ( $form['fields'] as &$field ) {
if ( $field->type != 'select' || strpos( $field->cssClass, 'populate-posts' ) === false ) {
continue;
}
// you can add additional parameters here to alter the posts that are retrieved
// more info: [http://codex.wordpress.org/Template_Tags/get_posts](http://codex.wordpress.org/Template_Tags/get_posts)
$posts = get_posts( 'numberposts=-1&post_status=publish' );
$choices = array();
foreach ( $posts as $post ) {
$choices[] = array( 'text' => $post->post_title, 'value' => $post->post_title );
}
// update 'Select a Post' to whatever you'd like the instructive option to be
$field->placeholder = 'Select a Post';
$field->choices = $choices;
}
return $form;
}
Modification found at Winwar Media
- Apply pre-rendering to all forms, if select has class
function populate_posts( $form ) {
foreach ( $form['fields'] as &$field ) {
if ( $field->type != 'select' || strpos( $field->cssClass, 'populate-posts' ) === false ) {
continue;
}
// you can add additional parameters here to alter the posts that are retrieved
$posts = get_posts( 'numberposts=-1&post_status=publish&post_type=events' ); // update post_type here!
$choices = array();
foreach ( $posts as $post ) {
$choices[] = array( 'text' => $post->post_title, 'value' => $post->post_title );
}
// update 'Select a Post' to whatever you'd like the instructive option to be
$field->placeholder = 'Select Workshop';
$field->choices = $choices;
}
return $form;
}
add_filter('gform_pre_render', 'populate_posts');

Want to learn to pre-populate more field types? You can find more information about Gravity Forms pre_render here.