guus van de wal
Menu

EntityQuery example in Drupal 8

9 March 2022

The excellent views module (in Drupal Core) is probably sufficient most of the time but if you'd like to create a list of content programmatically you could also use a EntityQuery.

Let's say you'd want a list of blog items ... In your YOURTHEMENAME.theme file of your template you could add the following code to load the nodes and add a view mode as well (to use a specific template, in this case a teaser).

Now each page.html.twig has a variable {{ blog }} that you can render ...

php

/**
 * @param $vars
 * Load a view into pages and an entityQuery
 */

function YOURTHEMENAME_preprocess_page(&$variables) {
  // EntityQuery blogs.
  $query = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->condition('type', 'blog')
    ->sort('created', 'DESC');

  $nids = $query->execute();
  $nids = $nids;
  $view_mode = 'teaser';
  $entity = 'node';
  $langcode = 'en';

  if (!empty($nids)) {
    $nodes = Node::loadMultiple($nids);
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder(reset($nodes)->getEntityTypeId());
    $nodes_views = $view_builder->viewMultiple($nodes, 'teaser');
  }
  $variables['blog'] = $nodes_views;
}
Happy Theming 🤩