Drupal webforms submissions by form_key

drupal
Published

February 11, 2014

With the ease of entry for  basic use and API for extensibility, the Drupal webforms module is an indispensable tool. One snag with it, though, is that wherever it exposes the results of a submission in code, the submitted values are just expressed in a big 0-based numerically indexed array. Using this $submission->data array directly would make for hard-to-read and fragile code, and there doesn’t seem to be a function provided in webforms to give you the submitted data in an associative array.

Creating my own function to generate an associative array of results fortunately wasn’t that bad though, and seems like a valuable enough thing to make note of here.

/**
 * Returns an associative array of the submission data, instead of the
 * numerically indexed $submission->data
 *
 *  Inspired by http://drupal.stackexchange.com/questions/23607/how-do-i-access-webform-components-labels-on-the-congratulations-page
 *
 * @param int $nid The node id of the webform
 * @param int $sid The submission id.
 */
function webform_submission_data_keyed($nid, $sid) {
  $data = array();
  $node = node_load($nid);
 
  module_load_include('inc', 'webform', 'includes/webform.submissions');
  $submission = webform_get_submission($nid, $sid);
 
  foreach($node->webform['components'] AS $key => $component) {
    if(isset($submission->data[$key])) {
      $data[$component['form_key']] = $submission->data[$key];
    }
  }
 
  return $data;
}

This’ll give you a multidimensional associative array with the “machine name” of each field as keys, and arrays as values. The subarrays are 0-based numeric indicies to one or more response values the user selected.

If you wanted the human names as keys, use \(data\[\)component[‘name’]] = \(submission->data\[\)key].