Issue with dynamically populating address fields [RESOLVED]

Using the gform_pre_render_ hook I receive the error when attempting to populate the default values:

Fatal error : Uncaught Error: Attempt to assign property “defaultValue” on array in…

This is the code I am using:

add_filter( 'gform_pre_render_'.$gravity_form_id, 'ebd_populate_form_with_data' );
function ebd_populate_form_with_data( $form ){
	$post_id_cid = false;
	if(!empty($_GET['cid'])) {
        $post_id_cid = base64_decode(urldecode($_GET['cid']));
    }
	$address_fields = array(
		'address',
		'city',
		'state',
		'zip'
	);
	foreach( $form['fields'] as &$field ) {
		$input_name = $field['inputName'];

		if ($field['type'] == 'address' && is_array($field['inputs'])) {
			foreach ($field['inputs'] as $address_field) {
    			$input_name = $address_field['name']; // why is this not inputName?
    			if ($input_name && in_array($input_name, $address_fields)) {
    				$current_value = get_post_meta($post_id_cid, $input_name, true);
    				if ($current_value) {
    					$address_field->defaultValue = $current_value; // error
    				}
    			}
    		}
		}

	}

    return $form;
}

The slugs in the $address_fields array are the same as the slugs in my custom post type for storing the data. Also, I am using these slugs in their respective fields in the “Parameter Name” fields after checking “Allow field to be dynamically populated” when creating the form.

Setting ->defaultValue works with other text based fields. Why is it not working for addresses? Is there another way to do this?

The code uses array access where object access should be used, and object access where array access should be used. Fields are objects, their inputs are arrays. Try this approach in the fields foreach:

if ( $field->type == 'address' && is_array( $field->inputs ) ) {
	foreach ( $field->inputs as &$input ) {
		$input_name = rgar( $input, 'name' );
		if ( $input_name && in_array( $input_name, $address_fields ) ) {
			$current_value = get_post_meta( $post_id_cid, $input_name, true );
			if ( $current_value ) {
				$input['defaultValue'] = $current_value;
			}
		}
	}
}
2 Likes

That’s what I was missing. Thank you so much for your help.