Drupal 8: execute a view programmaticaly

Deel deze pagina

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

// 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()

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

Vraag uw gratis websiteanalyse aan!

Brengt uw website niet het rendement die u voor ogen had?
Blijft het aantal klanten op uw website achter?

Vraag dan nu uw gratis website analyse aan en onze expert Louis vertelt u in een 5-minuten video waar de grootste problemen zitten.