Hello everyone. This is my first attempt to dynamically populate a dropdown list using gravity forms. My goal is to pull the data from an API. But for now, I’m just trying to get the list to populate with any data. I have pieced together the code below into a plugin but none of the hooks even show as loaded in query monitor and the dropdown is empty. I have checked the form title and the cssClass and both are correct. Thanks in advance for any help.
<?php
/*************************************************
Grab Names for Dynamic Gravity Form Dropdown
**************************************************/
//Create Gravity Forms filter
add_filter( 'gform_pre_render', 'populate_choices' );
//Note: when changing choice values, we also need to use the gform_pre_validation so that the new values are available when validating the field.
add_filter( 'gform_pre_validation', 'populate_choices' );
//Note: when changing choice values, we also need to use the gform_admin_pre_render so that the right values are displayed when editing the entry.
add_filter( 'gform_admin_pre_render', 'populate_choices' );
//Note: this will allow for the labels to be used during the submission process in case values are enabled
add_filter( 'gform_pre_submission_filter', 'populate_choices' );
function populate_choices($form) {
// Retrieve mock data
if ( $form['title'] != "BusinessClassification") return $form;
$vendorNames = get_mock_data();
// Populate choices for select fields
foreach ($form['fields'] as &$field ) {
if ($field->type == 'select' && strpos( $field->cssClass, 'company-dropdown') !==false){
$field->choices = array(); // Clear existing choices
foreach ($vendorNames as $option) {
$field->choices[] = array('text' => $option, 'value' => $option);
}
}
}
return $form;
}
function get_mock_data() {
// Simulate data retrieval
$contracts = array(
array('name' => 'Vendor 1'),
array('name' => 'Vendor 2'),
array('name' => 'Vendor 3')
);
// Extract unique vendor names
$vendorNames = array_unique(array_column($contracts, 'name'));
return $vendorNames;
}
?>