Dynamically generate List Dropdown choices
The gravitywp_list_dropdown_choices filter of List Dropdown lets you set or change the choices of a dropdown column in a Gravity Forms List Field with PHP. Use it when the choices come from another source, such as your products, posts or an external system, instead of the list in the form editor.
Usage
The filter passes 5 arguments:
add_filter( 'gravitywp_list_dropdown_choices', 'my_custom_function', 10, 5 );
The choices you return are used for columns where Enable Dropdown select is ticked in the form editor.
Parameters
- $drop_down_choices – Array of dropdown choices, each with a
valueand atext(label) property. - $field – The Field Object.
- $column – The column name (label). An empty string in a single-column List Field.
- $value – The current value. When the dropdown is shown, this is the value of the cell. When the add-on looks up the label of a stored value, this is the stored value of the List Field as a serialized string (in a single-column List Field: the value of the row).
- $form_id – The form id.
Example
This example populates the List Field Dropdown column ‘Select Product’ for field with ID 1 and form with ID 514 with 3 products.
/**
* Function: gravitywp_list_dropdown_choices.
*
* @param array $drop_down_choices Array of dropdown choices.
* @param GF_Field $field The Field Object.
* @param string $column The column name (label).
* @param string $value The current value.
* @param int $form_id The form id.
*
* @return array
*/
function gravitywp_list_dropdown_choices( $drop_down_choices, $field, $column, $value, $form_id ) {
if ( $form_id == 514 && $field->id == 1 && $column == 'Select Product' ) {
$drop_down_choices = array(
array(
'value' => 'p1',
'text' => 'Product 1',
),
array(
'value' => 'p2',
'text' => 'Product 2',
),
array(
'value' => 'p3',
'text' => 'Product 3',
),
);
}
return $drop_down_choices;
}
add_filter( 'gravitywp_list_dropdown_choices', 'gravitywp_list_dropdown_choices', 10, 5 );
Notes
- Show Values must be on for the column to save the values you return (
p1,p2,p3in the example). Without Show Values, the label is also the saved value. - The filter also runs when the add-on replaces a stored value with its label, for example in the entry detail or a notification (multi-column List Fields with Show Values on). Return the same choices in both cases, so every stored value finds its label.
- A Placeholder set for the column is added as the first option after the filter has run, so you don’t need to add it yourself.
Placement
You can place this code in the functions.php file of your (child) theme.