EntityQuery example in Drupal 8

August 12th, 2019

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 ...

 * @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 🤩

Do you have something useful and positive to say about this article?

Up next:

Debugging Drupal 8 Twig templates with Xdebug

February 19th, 2018

Ever wondered what variables live in your Drupal 8 templates and how to debug them properly? 🤔
Enabling twig debugging in sites/default/services.yml is the first step: (note that this is a Drupal 8.4.5 version)