简体   繁体   中英

How do I remove unnecessary options from a select field in a Drupal form?

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'] = $foo;
}

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.

Under your view argument there should be a section called " Validator options " with "" Action to take if argument does not validate under it. Depending on what you want shown, you should be able to display all values or display an empty page.

I found a solution that works, but it's somewhat hackish. I force the form to think that it's validated, and it doesn't complain anymore, with the following line at the bottom of the function:

$form['foo']['#validated'] = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM