1

I am using exposed filters in Views to give user opportunity to select attribute. I used field with taxonomy term as exposed filters.

As a result, exposed filter shows all possible variants for this field (all terms), instead which really were used in this material. I mean, that user can select any term from vocabulary even if I did not use this term in this content type material. How to hide unused terms in exposed filters?

2

The below code comes from a current project of mine. I've made it more generic for your purposes, so it's untested. You'd need to modify the query depending on your usage - it's going to throw errors if you use as-is.

<?php    
// Add this to a custom module, replace "mymodule" with your module name
function mymodule_form_views_exposed_form_alter(&$form, &$form_state) {
  //dsm($form); // Display available form vars
  $field_id = 'id_assigned_in_views'; // Change for the field ID in question.
  // Only alter forms with the necessary field.
  if (isset($form[$field_id])) {
    // Do your entity_field_query or db_query here
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'taxonomy_term')
      ->entityCondition('bundle', array('tags'))
      ->propertyOrderBy('weight');
    $result = $query->execute();
    $terms = $result['taxonomy_term'];
    // Add a default so the filter is optional.
    $options = array('' => t('- All -'));
    foreach($terms as $tid=>$term) {
      //dpm($term);
      $options[$tid] = $term->name;
    }
    // Alter the field.
    $form[$field_id]['#type'] = 'select';
    $form[$field_id]['#options'] = $options;
    $form[$field_id]['#size'] = 1;
  }
}
?>
  • Thank you for help, but is it possible to avoid code? Just by mouth clicking? – user38998 Nov 24 '14 at 10:06
  • I don't think this is default behaviour out of the box. Unfortunately there's a point at which 'mouth clicking' isn't enough. Here's a more verbose solution specific to your needs. wearepropeople.com/blog/… – murraybiscuit Nov 24 '14 at 10:12
  • OK. But how I can add code to Views? – user38998 Nov 24 '14 at 11:24
  • As mentioned in the answer: Add this to a custom module, replace "mymodule" with your module name. Enable the module, and customize More > Filter identifier in your views exposed filters setup to match the one in your code. – murraybiscuit Nov 24 '14 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.