2

I have a view and I want to get it's results.

$nview = views_get_view('tasks');
$nview->set_display('page');
$nview->pre_execute();
$nview->execute();

If I have 'nid' filter added to my view, I can modify it and get my view filtered.

$nview = views_get_view('tasks');
$nview->set_display('page');
$nview->pre_execute();
$nview->display['page']->handler->handlers['filter']['nid']->value['value']=180;
$nview->display['page']->handler->handlers['filter']['nid']->operator='=';
$nview->execute();

But what do I need write to add a filter if no filter present in view settings of my view?

$nview = views_get_view('tasks');
$nview->set_display('page');
$nview->pre_execute();

//some code here

$nview->execute();

UPD: Unfortunately, I can't use hook_views_query_alter because I need to use my code in my custom function which accepts view's name as an argument. My target is to alter any view which name passed as an argument to my custom function. So I need to alter filter/query only if I need get view's result and the view executes from my function. But if the view executes from it's page or block it needs to be executed without altering.

3

Another way is to add the filter as an exposed filter in the view and then set it programmatically like this:

// Set created date range filter.
$item = $view->get_item($display_id, 'filter', 'created');
$item['value']['min'] = $settings['min'];
$item['value']['max'] = $settings['max'];
// Disable exposed filter in UI, for programmatic filter.
$item['exposed'] = FALSE;  
$view->set_item($display_id, 'filter', 'created', $item);

That should come before $view->pre_execute();

You can also add a completely new filter in a similar way, by building up a valid $item to use with $view->set_item.

0

If you want to add a filter on your view when it is not defined in the view UI you can use hook_views_query_alter

Something like this:

function MYMODULE_views_query_alter(&$view, &$query) {
  dpm($view, __FUNCTION__);
  dpm($query, __FUNCTION__);
  if ($view->name === 'your_view_machine_name') {
    // Alter query.
    $query->where....
  }
}
  • Unfortunately your solution is not good for me. Please read UPD in my question. – Sergey Kravchenko Mar 1 '15 at 6:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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