Entity Queries in Drupal 8, how to find entity by type and cutsom field value and render them programmaticaly

Jun
2020
26

Drupal Core Views module is very sufficient most of the time but sometimes you need to create a list of content programmatically. This is where you could use EntityQuery.

Let's say you'd want a list of custom api blog items imported to your website per specific cron tasks. What you have to do is create into your module file for example an Entity Query Function and check every time if the specific article (by api id) exists or not.

So this is the code
<?php
  
function article_exists_to_db($api_article_id){

   
$query = \Drupal::entityQuery('node')
              ->
condition('type', 'article')
              ->
condition('field_api_article_id', $api_article_id);
     
$nids = $query->execute();

      if (!empty(
$nids)){
        return
true;
      }

      return
false;

    }
?>
and then in another function if there are nodes print them
<?php
  $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;
?>
Cats: 
this is an arrow pointing back to the top of the page