Entities Basics

A large amount of the data stored by Drupal is now encapsulated in entities, which keep the developer from having to know where and how the data is stored.  The methods used are pretty straightforward, but the key to using them is knowing the correct machine name for the entity and its class name.  To help with this, a list of common entities has been assembled.

<?php

/* Loading a single entity, such as a single user, is pretty easy: */

$user = \Drupal\user\Entity\User::load('admin');

/* To load the entire list of users, you use loadMultiple() instead of load() */

$userList = \Drupal\user\Entity\User::loadMultiple();

/* To load a specific list of users, just feed loadMultiple() and array of entity
   IDs.  To get a list of IDs that fit a search criterion, use the entityQuery()
   method, like so: */

$userUids = \Drupal::entityQuery('user') -> condition('status', 0) -> execute();

/* That gets everyone who has been blocked.  Note that you can chain multiple
   conditions together: */

$userUids = \Drupal::entityQuery('user') -> condition('status', 0) -> condition('created', time() - (60*60*24*30), '>')-> execute();

/* That gets everyone who has been blocked and created within the last thirty
   days.  Note the third parameter of '>' in the new condition() to specify the
   type of comparison.  By default, the comparison is simply equals or "=="
   in MySQL terms. */

/* Chaining conditions is effectively ANDing them together.  To OR conditions,
   do the following: */

$query = \Drupal::entityQuery('user');
$orGroup = $query -> orConditonGroup() -> condition('status', 0) -> condition('created', time() - (60*60*24*30), '>');
$userUids = $query -> condition($orGroup) -> execute();

/* Someone with better object-oriented experience might be able to condense
   that down more, but what's show does work */

/* You can also sort your results with the same kind of chaining technique (the
   second parameter for sort direction - 'asc' or 'desc' - is optional and
   defaults to 'asc') */

$userUids = \Drupal::entityQuery('user') -> condition('status', 0) -> sort('name', 'asc') -> execute();

/* Once you have a list of entity IDs, just feed them to loadMultiple() */

$userList = \Drupal\user\Entity\User::loadMultiple($userUids);