How to create a pre built list for webform in Drupal 6/7
Hello folks.
Sometimes we require to collect information from users, and a webform is a good option for that, but the problem comes when you need to present a variable list of options.
Imagine you want to allow user to request a role promotion, that means the user can fill out a form and select from a list the role he wants to get.
In an ideal world, this list of roles must be dynamically, to shrink or grow, when you delete or add new roles in your system. This simple task could be a nightmare in webforms.
Well for this kind of problem we can solve quickly using a hook available for webform in Drupal 6 and 7 hook_webform_select_options_info.
1. Implement hook_webform_select_options_info.
Create a custom module to implement hook_webform_select_options_info and define our custom pre built list. Check the sample listed below:
/**
* Implementation of hook_webform_select_options_info().
* See webform/webform_hooks.php for further information on this hook in the Webform API.
*/
function custom_webform_pre_build_list_webform_select_options_info() {
$items = array();
$items['user_roles'] = array(
'title' => t('Roles'),
'options callback' => 'custom_webform_pre_build_list_user_roles'
);
return $items;
}
/**
* Build an options list to be used with webforms select list based in drupal roles
*/
function custom_webform_pre_build_list_user_roles() {
$roles = user_roles();
$contentarray = array();
$contentarray[0] = t("Select user role");
foreach ($roles as $role) {
$contentarray[$role] = t($role);
}
return $contentarray;
}
The hook_webform_select_options_info will register our custom pre built list and will be avaiable for all webform in our drupal system.
Each pre built list have to be tied to a custom callback function and we need to return an array with all the options we want to present to our users.
2. Enable new pre built list in a webform
We need to create a select webform component and select out pre built list option. check image #1 attached.
3. Enjoy.
Now when you load a webform you can select an option from our new pre built list. check image #2 attached.
You can download a full module with this sample attached in this post.
Enjoy IT.
enzo
| Attachment | Size |
|---|---|
| 1.14 KB |









