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.

To get below code working, we must need to check the checkbox "Limit list to selected items" in exposed filter form.

Here's how you can alter the values in exposed filters in views:

<?php
 
function MODULE_NAME_views_pre_view(&$view, &$display_id, &$args) {
    if (
$view->name == 'VIEW_NAME') {
     
// Select allowed (root level) categories
     
$query = db_select('taxonomy_term_data', 'ttd');
     
$query->join('taxonomy_term_hierarchy', 'tth', 'tth.tid = ttd.tid');
     
$query->condition('tth.parent', 0) // Select terms at root level in category vocabulary
           
->condition('ttd.vid', 1) // 1 is category vocabulary ID
           
->fields('ttd', array('tid')); // select tid to set allowed values.

     

$allowed_categories = $query->execute()->fetchAllKeyed(0, 0);

     

// Set value to exposed filters.
     
$view->display['page_1']->handler->options['filters']['field_category']['value'] = $allowed_categories;
    }
  }
?>

In the above sample code, I've implemented hook_views_pre_view, which provides me entire view object which includes all fields inside views, header, footer, filters, sort, etc.

In this hook, I've first checked my view name. Then I've selected all root level category terms and passed that to value array in filters array in my view. (page_1 is my display of view, which will be shown to user)

Reference: