How do I remove unnecessary options from a select field in a Drupal form?
- by thismax
I'm using the better_exposed_filters module to create a set of exposed filters for a view. One of the filters is being displayed as a select field, and I would like the field to only display options that are actually associated with content in the database.
Currently, I am doing this using the hook_form_alter() method. For simplification, in the following example the field is called 'foo' and the content type with that field is called 'bar':
function my_module_form_alter(&$form, $form_state, $form_id) {
// Get all the values of foo that matter
$resource = db_query('select distinct field_foo_value from {content_type_bar}');
$foo = array();
while($row = db_fetch_object($resource)) {
$foo[$row->field_foo_value] = $row->field_foo_value;
}
$form['foo']['#options'] = $manufacturers;
}
This works great -- the form displays only the options I want to display. Unfortunately, the view doesn't actually display anything initially and I also get the following error message:
An illegal choice has been detected. Please contact the site administrator.
After I filter options with the form once, everything seems to work fine.
Does anyone know how I can solve this problem? I'm open to an entirely different way of weeding out filter options, if need be, or a way that I can figure out how to address that error.