Trivali webdevelopment

Drupal 8: execute a view programmaticaly

Sometimes you want to call a view in code and do something funky with it. The Drupal 8 way is similar to the D7 way, but ofcourse OO.

In the example below, we also add 2 filter arguments. Beware that you expose those filters on the view admin page. If you don’t expose them, you won’t be able to change them via the code.

Here’s how it’s done:

// The machine name of your view
$viewname = ‘machine_name_of_your_view’;

// Get the view
$view = \Drupal\views\Views::getView($viewname);

if (!$view) {
// The view could not be loaded. Add a watchdog message and leave the function
\Drupal::logger(‘module_name’)->error(‘View @view not found’, array(‘@view’ => $viewname));
return false;
}

// set the display machine name
$view->setDisplay(‘default’);

// Set arguments for exposed filters
// Note that you always need to use an array.
// The arguments are passed in the order as they appear on the view
$view->setArguments(array($arg1, $arg2));

// Execute the view
// This function does not do any access checks on the view. It is the responsibility of the caller to check $view->access()
$view->preview();

if (count($view->result)) {
// Do funky thinks with your results
} else {
drupal_set_message(‘No results found’);
}