Providing dynamic select options to Webform module for Drupal
The Webform module for Drupal is tremendously useful, and with the 3.x release, it has become much easier to work with.In this tutorial, I am going to explain how to dynamically populate Webform options in Drupal.
The scenario
Why would you want to do this? Let's suppose you are using Webform to allow your site users to register for upcoming events. In the old days it worked like this: you added a select component to your Webform, and then hand-entered the upcoming events. When the date of an event passed, you would have to go back to your component and update the list. It was either that, or you had to implement hook_form_alter, which is no fun.
With Webform 3.x, quicksketch has provided us with hook_webform_select_options_info(), which we can use to provide our dynamic select options to Webform 3.x.
Implementing hook_webform_select_options_info()
First we need to create a module. In our module file we would add the following:
This function is providing two items to Webform, "Story nodes" and "A view". You can optionally define a file callback if you want to separate keep a clean separation of your core module functions and the callback you are providing for Webform. Check out webform_hooks.php in your webform module folder for more information.
At this point, all we've done is tell Webform that there are two new options for the select options component. Now we need to provide the functions for the callbacks that we specified above:
The function above is a simple example of a database query. It selects all nodes of the story type and orders them by title. Not terribly useful, but you can tweak the query to provide the results you are looking for.
For most folks, an easier and more sustainable option will be to create a View of the nodes that you want to display to your users, then implement the function below:
This will then return an array of items based on the View that you defined. If you end up using Views, I would strongly recommend exporting your View as a module and adding it as a dependency in your new module's .info file.
Usage
Now in your webform, click on "Form Components" and under type pick "Select options". Click on "Add", and under "Load a pre-built options list", pick the option you defined above.
And that's it! Now any time you add or delete a Story node, or the results returned by 'my_sample_view' change, the options displayed to the user in your Webform will also change.
The tarball of the code is attached.
Questions? Comments? Let me know.