Skip to content
Advertisement

Gravityforms populate selected value on dropdown within theme functions.php

I am working in gravityforms to pre-populate a form with database values dynamically, which is working. I need to be able to specity which of these options is selected by default when the form is built, but I can’t find the option to do so. I have seen the placeholder, but I presume this doesnt actualy select anything on the dropdown. I have been unable to find any docs or references that allow me to set the “selected” options once I have built all the text/value pairs in the array and set the choices.

The function (which I have redacted here) works fine and populates the field, I just need to populate a placeholder and/or default selected value.

add_filter('gform_pre_render_1', 'getFieldValues');
add_filter('gform_pre_validation_1', 'getFieldValues');
add_filter('gform_pre_submission_filter_1', 'getFieldValues');
function getFieldValues($form) {
    global $wpdb;
    foreach ($form['fields'] as $field) {
        if ($field->id == '40') {
            // get the list of values from the Database
            $list1Q = "SELECT <data> FROM <table> WHERE <params> = <value>";
            $list1R = $wpdb->get_results($list1Q);
            // Generate a nice array that Gravity Forms can understand
            if (!empty($list1R)) {
                $list1A[] = array();
                foreach ($list1A as $listItem) {
                    // Add current value to the array for dropdown choices
                    $list1C[] = array('text' => $listItem->variable, 'value' => $listItem->variable);
                 }
            }
            // Set choices to field
            $field->choices = $List1C;
            ***** THIS IS WHERE I WOULD LIKE TO SET THE SELECTED VALUE *****
        }
    }
    return $form;
}

If there is a better way to go about populating this field, I am open to suggestions at it seems that the form loads a bit slow using this method. Otherwise, I would love to know how to set a selected choice value after populating the choices.

Advertisement

Answer

the quick answer is, there is an option that i found for “isSelected” that can be included in the array when defining choices. I added a ternary operation to match on what I wanted selected and it set the “selected value for me.

$isSelected = ($listItem->variable == "value I want to select") ? true : false;
$list1C[] = array('text' => $listItem->variable, 'value' => $listItem->variable, 'isSelected' => $isSelected);

Adding the ternary choice and changing the array push allowed me to set a value as selected.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement