Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Programmatically Adding Pre-Built Option Lists to Drupal Webforms

Parent Feed: 

I'm a huge fan of the Webform module (and building Drupal forms in general), and I just today noticed a feature I hadn't previously taken advantage of. This is the ability to programmatically add what are called "pre-built" option lists that can be used in your webforms.

Webform pre-built options list in action

Let's say that you want the user to select his/her age from a dropdown. Age possibilities range from 1-100. Without a pre-built option list, you'd have to type in 0|0, 1|1, 2|2, etc. into the "options" field. You can now do this using the webform api and a small custom module for your site.

In your custom module, you have to declare your new options list. Here's an example:

<?php
/**
* Implementation of hook_webform_select_options_info().
* See webform/webform_hooks.php for further information on this hook in the Webform API.
*/
function YOURMODULENAME_webform_select_options_info() {
 
$items = array();
 
$items['one_onehundred'] = array(
   
'title' => t('Numbers 1-100'),
   
'options callback' => 'YOURMODULENAME_options_one_onehundred'
 
);
  return
$items;
}
?>

After that, you need to write a function that spits out the options list. For this example, that looks like:

<?php
/**
* Build an options list for use by webforms.
*/
function YOURMODULENAME_options_one_onehundred() {
 
$options = array();
  for (
$x=1; $x <= 100; $x++) {
   
$options[$x] = $x;
  }
  return
$options;
}
?>

After that, just enable your custom module, and you should be able to use your new pre-built options list in your webforms. Check out the webform_hooks.php file (included in the Webform module directory) for more information.

Note: This is for Drupal 6 and Webform 3.0-beta 5.

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web