Adding fields to your webform programatically

By Selwyn Polit, 25 August, 2021

Using Drupal 7, I needed to programattically add a useragent field (webform calls these components) and a url field to my webform nid 7477.  The url field is a hidden field of type: Hidden element (less secure, changeable via JavaScript.)  If you leave off the extra array in the url definition, it will be the normal hidden type.  You can see this when you click the edit button for this component.  I hope someone finds this useful.

function mymodule_update_7118() {


  module_load_include('inc', 'webform', 'includes/webform.components');
  $components = array();
  $components[0] = array(
    'name' => 'useragent',
    'form_key' => 'useragent',
    'type' => 'hidden',
    'mandatory' => 0,
    'weight' => 8,
    'pid' => 0,
    'value' => '%server[HTTP_USER_AGENT]',
  );

  $components[1] = array(
    'name' => 'url',
    'form_key' => 'url',
    'type' => 'hidden',
    'mandatory' => 0,
    'weight' => 9,
    'pid' => 0,
    'value' => 'Base URL will be stored here',
    'extra' => array(
      'hidden_type' => 'hidden',
      'conditional_operator' => '=',
      'private' => 0,
    ),
  );
  foreach($components as $component) {
    $component['nid'] = 7477;  // The node id of your webform
    $node->webform['components'][] = $component;
    webform_component_insert($component);
  }
}

I also got to programmatically fill out the url field using the following code:

function store_webform_submission_presave($node, $submission) {
  global $base_url;
  $local_base_url = $base_url . $_SERVER['REQUEST_URI'];

  // Get webforms to store the base_url so we can tell if we are on desktop
  // or mobile.
  if (isset($submission->data[10]['value'][0])) {
      $submission->data[10]['value'][0] = $local_base_url;
  }
}

This stored the complete url ie http://www.mysite.com/contact-us