Snippets

range() and pager() Drupal 8

$query = \Drupal::entityQuery('node');
$new_articles = $query->condition('type', 'article') 
->condition('status', 1)  // Only return the newest 10 articles
->sort('created', 'DESC') 
->pager(10) 
->execute(); 

$not_quite_as_new_articles = $query->condition('type', 'article') 
->condition('status', 1)  // Only return the next newest 10 articles
->sort('created', 'DESC') 
->range(10, 10) 
->execute();

Drupal8 count()

$query = \Drupal::entityQuery('user');
$time = time();
$yesterday = $time - 60*60*24; 
$new_user_count = $query->condition('created', $yesterday, '>=')
 ->count()
 ->execute(); 

Drupal8 sort()

$query = \Drupal::entityQuery('user'); 
$time = time(); 
$yesterday = $time - 60*60*24; 
$new_users = $query->condition('created', $yesterday, '>=') 
->sort('created', 'DESC') 
->execute();

Drupal8 exists() or notExists()

$query = \Drupal::entityQuery('node'); 
$untagged_articles = $query->condition('type', 'article') 
->notExists('field_tags') 
->execute();

Drupal 8 Entity Query Conditions

$query = \Drupal::entityQuery('node');
$query = \Drupal::service('entity.query');

// To get a list of published articles
$node_ids = $query->get('node') 
->condition('type', 'article') 
->condition('status', 1)
->execute();

// To find all users with the Administrator role.
$admin_user_ids = $query->get('user') 
->condition('roles', 'Administrator', 'CONTAINS') 
->execute();

Druoal 8 Get nodes from a query

$query = \Drupal::entityQuery('node')
  ->condition('type', 'article'),
  ->condition('field_foo', 'bar');
$nids = $query->execute();
$nodes = $node_storage->loadMultiple($nids);
 
foreach ($nodes as $n) {
  echo $n->title->value; // "titles"
  // do whatever you would do with a node object (set fields, save, etc.)
  $n->set('title', "Test Title");
  $n->save();
}

Drupal 8 Load a node by NID

$nid =36;     // node id
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$node = $node_storage->load($nid);
echo $node->id();  // 36

Update Drupal module version using composer

Update Drupal module version using composer

Get the list of outdated modules: 

composer outdated "drupal/*"

Install module update:

composer update drupal/module_name --with-dependencies

Then, run the database updates /update.php & Clear the drupal cache :)