Skip to content

Instantly share code, notes, and snippets.

@mjn666
Created September 15, 2015 00:09
Show Gist options
  • Save mjn666/51dbc5aae0620e8b71f9 to your computer and use it in GitHub Desktop.
Save mjn666/51dbc5aae0620e8b71f9 to your computer and use it in GitHub Desktop.
How to pre-select a choice/option in Gravity Forms using a dynamic field
/**
* Pre Select a dropdown choice/option in Gravity Forms
*
* Create a dynamic list of dropdown choices from a custom post type
* Based on the current page, pre-select a choice in the drop down
*
* @var howto_dynamic_field = the dynamic field set in Gravity Forms on the field group under the Advanced tab
* @var howto_post_type = Your custom post type you are listing in the drop down
*
*/
add_filter( 'gform_pre_render_1', 'howto_preselect_dropdown' );
add_filter( 'gform_pre_validation_1', 'howto_preselect_dropdown' );
add_filter( 'gform_pre_submission_filter_1', 'howto_preselect_dropdown' );
add_filter( 'gform_admin_pre_render_1', 'howto_preselect_dropdown' );
function howto_preselect_dropdown( $form ) {
global $post;
$current_post = $post->post_name;
foreach ( $form['fields'] as &$field ) {
if ( $field->type != 'select' || strpos( $field->inputName, 'howto_dynamic_field' ) === false ) {
continue;
}
$args = array(
'post_type' => 'howto_post_type',
'order' => 'ASC',
'orderby' => 'title',
'posts_per_page' => -1
);
$posts = get_posts( $args );
$choices = array();
foreach ( $posts as $post ) {
if ($current_post === $post->post_name) {
$choices[] = array( 'text' => __($post->post_title, 'ozh_reap'), 'value' => sanitize_title($post->post_title), 'isSelected' => true );
} else {
$choices[] = array( 'text' => __($post->post_title, 'ozh_reap'), 'value' => sanitize_title($post->post_title));
}
}
$field->placeholder = 'Select';
$field->choices = $choices;
}
return $form;
}
@mjn666
Copy link
Author

mjn666 commented Sep 15, 2015

How to pre-select a dropdown in Gravity Form using a Dynamic Field

Make sure the howto_dynamic_field matches the Parameter Name you define in Gravity Forms for your field under the Advanced Tab > Allow field to be populated dynamically.

@idpokute
Copy link

idpokute commented Dec 5, 2016

Thank you for sharing this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment