Dynamically Populate a Gravity Forms Field from a Pods Related Field

Dynamically populating a Gravity Form field without creating a Pods Feed for the form.

With Pods Gravity Forms feeds, you can use the interface to setup a connection between a Pod field and a Gravity Form field. In some cases you may not want to setup a feed and just have the Gravity Form field populate the options directly from a specific related field from a Pod.

<?php
add_filter( 'gform_pre_render', 'add_my_dynamic_select' );

/**
 * Add my dynamic select. Consider renaming this function and the also function filter above.
 *
 * @param array $form GF form.
 *
 * @return array GF form.
 */
function add_my_dynamic_select( $form ) {
	// This is the form ID and field ID we want to make dynamic.
	$form_id   = 1;
	$field_id  = 12;
	$pod_name  = 'my_pod';
	$pod_field = 'my_related_field';

	// Only add our dynamic select code if on the right form ID.
	if ( $form_id !== $form['id'] ) {
		return $form;
	}

	// Get the pod object.
	$pod = pods( $pod_name );

	// If the pod was not found, don't try to setup dynamic select.
	if ( ! $pod || ! $pod->valid() ) {
		return $form;
	}

	// Get the related data from the pod field.
	$related_data = $pod->fields( $pod_field, 'data' );

	// If there is no related data or it wasn't a relationship field, don't try to setup dynamic select.
	if ( empty( $related_data ) ) {
		return $form;
	}

	// Pass the data into the dynamic select options.
	$options = array(
		'options' => $related_data,
	);

	// Add the dynamic select, Pods GF takes over from here on all other hooks.
	Pods_GF::dynamic_select( $form_id, $field_id, $options );

	return $form;
}

Questions