[Drupal 7][Views 3.x] How to programmatically render a view display passing exposed filter inputs via code using $view->exposed_input

| | 1 min read

This is how you would normally render a view display passing filter inputs via code:

  $view = views_get_view('view-name');
  $view->set_display('display-name');
  $view->is_cacheable = FALSE;
  $filter_1 = $view->get_item('display-name', 'filter', 'filter_1_id');
  $filter_2 = $view->get_item('display-name', 'filter', 'filter_2_id');
  $filter_1['value'] = "value1";
  $filter_2['value'] = "value2";
  $view->set_item('display-name', 'filter', 'filter_1_id', $filter_1);
  $view->set_item('display-name', 'filter', 'filter_2_id', $filter_2);
  dpm($view->render());

The problem with this method is that it sometimes fails when you are trying to filter on the node status (published/unpublished) - selecting 'unpublished' items does not work in some cases.

You can use the following method instead to render a view display with exposed filters, passing the filter inputs as follows:

  $view = views_get_view('view-name');
  $view->set_display('display-name');
  $view->is_cacheable = FALSE;  
  $view->exposed_input['filter_1_exposed_input_name'] = "value1";
  $view->exposed_input['filter_2_exposed_input_name'] = "value2";
  dpm($view->render());
  

For this, you first need to find the exposed input field name, structure.

For that, use the following piece of code:

  $view = views_get_view('view-name');
  $view->set_display('display-name');
  $view->is_cacheable = FALSE;  
  $view->execute();  
  dpm($view->exposed_raw_input);
  

With Devel module enabled, running this once, you will get the names, structures of the available exposed input filter fields. Here's a sample output of that:

views exposed raw input dpm