9

I have a page view with exposed filters. One of the filters is term vocabulary, and that's dropdown list, user can select only one category (term).

I want to set programmatically one term from dropdown list when I came from specific URL. I tried with views_query_alter where $category is tid.

 $set_exposed_input  = array();
 $set_exposed_input['field_category_tid'] = $category;

 if ($set_exposed_input) {
    $view->set_exposed_input($set_exposed_input);
 }
2

3 Answers 3

15

For drupal 7 you can use

$view->exposed_input[$key] = $value;

This is

$view->exposed_input['title'] = 'My title is a cat';

For a full example you can try this:

$name = 'name_of_view';
$display = 'page_1';
$alter = array('exposed' =>array('title' => 'title_value'));

$view = views_get_view($name);
$view->init_display($display);
$view->preview=TRUE;
$view->is_cacheable = FALSE;


if(isset($alter['exposed'])){
  foreach($alter['exposed'] as $key => $valor){

     $view->exposed_input[$key] = $valor;

  }
}

$view->pre_execute();
$output = $view->display_handler->preview();
$view->post_execute();

print_r($view->result);

Other way is using the views set_option function

$filters = $view->display_handler->get_option('filters');

foreach($alter['exposed'] as $key => $valor){
   $filters[$key]['value'] = $valor;
   $view->display_handler->set_option('filters', $filters);
}
6
  • 1
    where do you place this, in a view pre execute or something like that?
    – Mika A.
    Commented Apr 17, 2013 at 8:57
  • In the views tpl! And the full example, wherever, it has a load view function
    – rafinskipg
    Commented Apr 26, 2013 at 9:38
  • 1
    You can also add it to hook_views_pre_view Commented Aug 26, 2013 at 15:33
  • 6
    The tpl file should be used to display rendered content, not to set business logic. Please try one of the other myriad views hooks: api.drupal.org/api/views/views.api.php/7 Commented Oct 22, 2013 at 15:21
  • What about non exposed filter? I have very rare use case and I need to set filter value by custom code.
    – Codium
    Commented Dec 6, 2015 at 1:43
2

with Drupal 7.54 when you want to process the exposed filter programmatically, this is how you do it when you have a multiple valued field. The solution to see how to pass exposed filter is to follow how the URL is made.

Here: view_name?alias[1]=1

$view = views_get_view('view_name');
$view->init_display('display_id');

$filters = array('alias' => array('1'));
$view->set_exposed_input($filters);

$view->execute();

You can execute this from wherever you want. Preferably from the module file.

1

Set exposed filter value like this:

$view->exposed_input['field_category_tid'] = $category;

Your Answer

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

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