Pre-populate Gravity Forms List Field

This is a little snippet I put together when looking at using Gravity Forms dynamic population to pre-populate a list type field. The task in question had the list field value saved to user meta (via the User Registration add-on), so that’s why we’re checking to see if it’s empty before assigning the value, in case the user has already modified and saved newer information than the default.

<?php
/******************************************************
* gform_user_registration_user_data_pre_populate runs when data is pulled from user meta and displayed
******************************************************/
add_filter( 'gform_user_registration_user_data_pre_populate', 'gf_prepopulate_meta_mapped_data', 10, 3 );
function gf_prepopulate_meta_mapped_data( $mapped_fields, $form, $feed ) {
    $form_id = $form['id']; //Gets the form ID that is being pre-populated
    if($form_id == 24) {  //Runs only on form number 24
        //Array of list field values, just like you defined in your original example (no changes)
        $field_one_value = array(
            array(
                'Item' => 'Rent',
                'Cost per Month' => ' ',
            ),
            array(
                'Item' => 'Phone',
                'Cost per Month' => ' ',
            ),
            array(
                'Item' => 'Internet',
                'Cost per Month' => ' ',
            ),
            array(
                'Item' => 'Electricity',
                'Cost per Month' => ' ',
            ),
            array(
                'Item' => 'Add Option',
                'Cost per Month' => ' ',
            ),
        );
    
        //If there isn't something saved to the mapped meta field, then use the array above and map to field 1
        if(empty($mapped_fields[1])) {
            $mapped_fields[1] = maybe_serialize($field_one_value);
        }
    }
    
    return $mapped_fields;
}

Leave a Reply

Your email address will not be published. Required fields are marked *