Tech Blog :: Useful code snippet for Webform default values


Mar 17 '10 2:42pm
Tags

Useful code snippet for Webform default values

A little code snippet I expect to need again in the future: Drupal's Webform module lets <select> elements have default values, but if the default value isn't one of the actual items, it still shows as "select..." as the default. (This is important for validation: if the field is required but the top/blank/default value is in the value list, it'll be counted as valid.) This snippet in a hook_form_alter seems to do the trick:
function MODULE_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'webform_client_form_NID':  // put your actual nid or other identifier here
      // change default "select..." to default value if default value isn't one of the options
      $list = &$form['submitted']['FIELDSET']['LIST'];  // per your FAPI array
      if ( reset($list['#options']) === 'select...'   // unchanged from default
       && !empty($list['#default_value'])             // list has another default
       && !array_key_exists($list['#default_value'], $list['#options']) ) // its default isn't one of the options
      {
        // this is a little tricky b/c the blank-string 1st key is very important
        array_shift($list['#options']);
        $list['#options'] = array('' => $list['#default_value']) + $list['#options'];
      }
 
      break;
  }
}

Post new comment

Don't bother putting in spam links. They'll be set to rel=nofollow and will be removed and reported as spam shortly after submitting.

The content of this field is kept private and will not be shown publicly.
CAPTCHA
Are you human?