A problem I came up against recently was how to make one select box relate to another. I wanted to build my form so that when select box A was updated, select box B would refresh and show a list of options in the context of the value of select box A’s current value.
It was tougher than I expected it to be, but that may so more about me than anything else.
Here is a good article on dynamic select boxes in Drupal. Their approach is to use textfields to store each value and then use jQuery to create select boxes and add them to the page. It uses the excellent jQuery select boxes helper.
This is fine, but it doesn’t allow server side validation of your content, which I wanted. I might not really have needed it, but I wanted it.
One way around this would be to do keep things as above and create a module to do the post submission validation using one of the web form hooks. I took a slightly different approach.
My aim was:
- Use webform select box with my special list of values
- Allow webform validation
- Supply my own values to webform
- Use jQuery to update the select box at runtime
So, first off – how to get a webform to use your values in a selectbox. By default, webform lists provide lists for days of the week and US states. Countries API adds another list.
Creating your own list is actually very simple, it’s just a hook you need to add to a custom module:
function YOUR_MODULE_webform_select_options_info() { $items = array(); $items['LIST_ID'] = array( 'title' => t('LIST NAME'), 'options callback' => 'LIST_OPTIONS_FUNCTION' ); return $items; } function LIST_OPTIONS_FUNCTION() { //build item array $options['item-value'] = 'Item Label'; return $options; } |
When you load the settings page for a webform select box, you’ll now be able to select your new list.
This should set-up the form validation.
To make the client-side dynamic stuff work, I’m using Views 3 and Views Datasource (this let’s me output as JSON). The view is set-up with a page display, taking an argument as part of the URL.
I’m adding a javascript file to my webform page which contains my jQuery code.
$(function() { select = $("select#YOUR_SELECT_ID_1"); select.change(function(){ $.getJSON("/path-to-view/"+$(this).attr('value'), populateYourData); }); }); function populateYourData(data, textStatus) { select = $("select#YOUR_SELECT_ID_2"); select.removeOption(/./); for(i in data.nodes){ value = data.nodes[i].node.value; label = data.nodes[i].node.label; select.addOption(value, label); } select.val(""); } |
When referencing:
data.nodes[i].node.value; |
‘value’ is the label you gave the field in your view.
That’s it. A webform, a custom module, a view and some jQuery.
I may have made this harder than it needs to be.



