How to alter views exposed filter allowed value list


via -

Just came across a situation, where wanted to alter the allowed values in views exposed filter depending on users who are viewing them.

View allows site admin to expose its filter value to user, so they can apply different filters while viewing views output. But what if you need to show the allowed list depending on users.

For example, I've content type "articles" which has term reference field "field_category" which refers to vocabulary "category" which has child - parent relation in terms. To show all articles I've created a view and added exposed filter for field "field_category", which will allow users to filter results based on the category they are selecting. So when showing field_category filter to anonymous users I want restrict the filters to root terms only in category vocabulary.

Get raw version
  1. <?php
  2. function MODULE_NAME_views_pre_view(&$view, &$display_id, &$args) {
  3. if ($view->name == 'VIEW_NAME') {
  4. // Select allowed (root level) categories
  5. $query = db_select('taxonomy_term_data', 'ttd');
  6. $query->join('taxonomy_term_hierarchy', 'tth', 'tth.tid = ttd.tid');
  7. $query->condition('tth.parent', 0) // Select terms at root level in category vocabulary
  8. ->condition('ttd.vid', 1) // 1 is category vocabulary ID
  9. ->fields('ttd', array('tid')); // select tid to set allowed values.
  12. $allowed_categories = $query->execute()->fetchAllKeyed(0, 0);
  15. // Set value to exposed filters.
  16. $view->display['page_1']->handler->options['filters']['field_category']['value'] = $allowed_categories;
  17. }
  18. }
  19. ?> - See more at: