
Adding custom fields to Webform - Using the Webform API
I had a recent project where I used the Webform module to create a form for a client. We decided to use Webform in case they wanted to create additional forms in the future and so that they could more easily track submissions and make changes to the form, etc. There are some nice additions to the 3.x branch of Webform including the API. You can add dynamic fields to your form that are populated with data that lives either in the Drupal site, or ostensibly elsewhere by utilizing the Webform hooks.
I wanted to add a list of taxonomy terms from a specific vocabulary to the form so I used this hook, by implementing it in the site-specific module I'd already created to house the views for the site.
function hook_webform_select_options_info() {
$items = array();
$items['days'] = array(
'title' => t('Days of the week'),
'options callback' => 'webform_options_days',
'file' => 'includes/webform.options.inc',
);
return $items;
}
The 'title' array item is pretty self explanatory, this will be the title that is displayed in the Webform options drop down when you select "Load a pre-built option list".
The 'options callback' item is simply the name of the function that you'll write to assemble the data that will be in your drop down list.
The 'file' item is optional and gives you the option of creating a separate file for your webform functions if you end up having a lot of them.
Since I wanted to get a list of the items in a specific vocabulary, here was the code I wrote to accomplish that.
function mymodule_webform_select_options_info(){
$items = array();
$items['neighborhoods'] = array(
'title' => t('Boroughs'),
'options callback' => 'webform_borough_taxonomy',
);
return $items;
}
function webform_neighborhood_taxonomy(){
$borough = taxonomy_get_tree(2);
$items = array();
foreach ($borough as $item){
$items[] = $item->name;
}
return $items;
}
Then you create a select item in your webform, put in one or two dummy options, and select "Load a pre-built option list".
There's definitely a better way to do this instead of explicitly stating the taxonomy vocabulary ID in the taxonomy_get_tree function, but for my purposes I only needed something quick and dirty.

