Digital agency · Beervelde (Gent) · Drupal & WordPress

Drupal 10: execute a view programmaticaly

Blog

24 mei 2024 · 1 min lezen · door Kristof

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

Drupal

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::messenger()->addMessage('No results found');
}

Lees ook

Hulp nodig bij je website of marketing?

Een vrijblijvend gesprek van 30 minuten: we luisteren naar je doelen, kijken naar je huidige site en vertellen eerlijk wat we zouden doen. Geen verkooppraatje.

Stuur ons een bericht

Waarmee kunnen we helpen?

Vertrouwd door o.a.