Recursively pre-populate Webforms I am trying to pre-populate a webform based on the values from a third party service. 

I am using form_alter to start the processing and then using a recursive function to traverse the tree. I am passing the sub-form(part of a form of type fieldset) by reference, so that changes do carry forward.

Here is the code : 

function my_module_form_alter(&amp;$form, &amp;$form_state, $form_id) {
    $submitted = $form['submitted'];
    prepopulate_form($submitted, $value_array);
}

function prepopulate_form(&amp;$form, $value_array) {
  foreach ($form as $key =&gt; $settings) {
    if (is_array($settings) &amp;&amp; isset($settings['#type'])) {
      if ($settings['#type'] == 'fieldset') {
        prepopulate_form($form[$key], $value_array);
      }
      $value = 'Some logic to get the value from value arrya';
        dpm($value); // I am getting the expected output here.   
        $form[$key]['#default_value'] = $value; // The changes I make here are not being carried to the actual $form array I suppose
    }
  }
}


But the form is not getting pre-populated. I am not sure what I am missing here.

Any insights would help. Thanks !
The main problem is you are not passing the form array by reference so your values are never coming back into the form. Try this (note the ampersand on $form['submitted']):

function my_module_form_alter(&amp;$form, &amp;$form_state, $form_id) {
  $submitted = &amp;$form['submitted'];
  prepopulate_form($submitted, $value_array);
}


Otherwise you are only modifying the $submitted variable and not the actual form. 

Alternatively, you could also just pass $form['submitted'] into the prepopulate_form() function instead of using the $submitted variable and that would also work.

Plus, you are using $value_array, which does not exist, so you will need to pass actual values in.