Skip to content

Instantly share code, notes, and snippets.

@psaikali
Created January 4, 2019 13:43
Show Gist options
  • Star 37 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save psaikali/2b29e6e83f50718625af27c2958c828f to your computer and use it in GitHub Desktop.
Save psaikali/2b29e6e83f50718625af27c2958c828f to your computer and use it in GitHub Desktop.
Populate ACF select field options with Gravity Forms to select a specific form
<?php
/**
* Populate ACF select field options with Gravity Forms forms
*/
function acf_populate_gf_forms_ids( $field ) {
if ( class_exists( 'GFFormsModel' ) ) {
$choices = [];
foreach ( \GFFormsModel::get_forms() as $form ) {
$choices[ $form->id ] = $form->title;
}
$field['choices'] = $choices;
}
return $field;
}
add_filter( 'acf/load_field/name=submit_project_gf_form_id', 'acf_populate_gf_forms_ids' );
@SjorsHartwijk
Copy link

Great solution! How do i display the selected form on my page? The value from the select box is the form ID.

@psaikali
Copy link
Author

Hey @SjorsHartwijk

You're looking for the gravity_form() function, see https://docs.gravityforms.com/adding-a-form-to-the-theme-file/

@HeliumChris
Copy link

HeliumChris commented Apr 13, 2024

Thank you psaikali! This was so helpful for me. I was getting a php warning (running php 8+) with the original code, so I'm offering this version that worked for me.

*Note to others: remember to change 'your_field_name' to whatever you named your ACF Select field.


// Populate ACF select field options with Gravity Forms forms 
function acf_populate_gf_forms_ids( $field ) {
    if ( class_exists( 'GFFormsModel' ) ) {
        $choices = array(
            'none' => 'None'
        );

        $forms = \GFFormsModel::get_forms();

        if ( $forms ) {
            foreach ( $forms as $form ) {
                $choices[ $form->id ] = $form->title;
            }
        }

        $field['choices'] = $choices;
    }

    return $field;
}
add_filter( 'acf/load_field/name=your_field_name', 'acf_populate_gf_forms_ids' );


Here's the PHP code to render the shortcode:

<?php 
	$form_id = get_field('your_field_name');
	if ($form_id && $form_id !== 'none') {
	    $escaped_form_id = acf_esc_html($form_id);
	    echo do_shortcode("[gravityform id=\"$escaped_form_id\" title=\"true\" description=\"true\" ajax=\"true\" tabindex=\"4\" theme=\"gravity\"]");
	}
?>

*Edited to set the default field to "none"

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