0

I have a view which has a term reference exposed filter.

I want to set the default values of this exposed filter programmatically based on a certain condition.

I have tried the following code but the values are not selected in the filter.

function example_views_pre_build(&$view) {
  if ($view->name == 'events') {
    $tids = array(5, 6);
    foreach (tids as $tid) {
      $view->display[$view->current_display]->handler->handlers['filter']['field_category']->value[$tid] = $tid;
    }
  }
}

AND

function example_views_pre_view(&$view, &$display_id, &$args) {
      if ($view->name == 'events') {
        $tids = array(5, 6);
        foreach (tids as $tid) {
          $view->display[$view->current_display]->display_options['filters']['field_category']->value[$tid] = $tid;
        }
      }
    }

I also tried with form_alter, in form alter the values gets selected in the filter but then it does not display correct results after removing/applying again the filter.

2 Answers 2

1
function example_views_pre_build(&$view) {
    if ($view->name == 'VIEW_NAME') {
        $view->display[$view->current_display]->handler->handlers['filter']['field_country_tid']->value = array(55, 91);
    }
}

This code worked for me. Check your views module version as well. I am using Views 7.x-3.14.

4
  • mine is also 7.x-3.14 version :(
    – Ahmad
    Mar 2, 2017 at 14:38
  • have you tried with BEF checkboxes? I'm using BEF checkboxes
    – Ahmad
    Mar 2, 2017 at 14:43
  • Forgot to mention one more thing - I have tested this with multi-value select field, not checkbox.
    – Jose D
    Mar 3, 2017 at 16:14
  • checkboxes do behave similar to a select element, @Ahmad the problem with your code is that views expect filters to be a numeric indexed array, using $tid as key will not work.
    – d70rr3s
    Dec 10, 2019 at 13:49
0

I used this for multiple value filter (D7):

function MY_MODULE_views_pre_build(&$view) {
  if ($view->name == 'VIEW_NAME') {
    $view->filter['FIELD_NAME']->value = array('nouveau', 'pending', 'complete', 'waitlist', 'held', 'canceled');
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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