FRANKO ANTIČEVIĆ
"Entities are the basic building blocks of Drupal's data model." - drupalize.me
"An entity would be one instance of a particular entity type such as a comment, taxonomy term or user profile or of a bundle such as a blog post, article or product."
- drupal.org
Entity type
Bundle
Entity
Field
Entity group
// Using static methods
$node = \Drupal::entityTypeManager()->getStorage('node')->load(22)
// When service container available
$service = \Drupal::service('entity_type.manager')->getStorage('node');
$node = $service->load(22);
// Loading multiple entities
$entity = \Drupal::entityTypeManager()->getStorage($entity_type)
->loadMultiple(array(22, 14, 8));
// With procedural wrapper
$node = entity_create('node', array(
'title' => 'Make blogs great again',
'body' => 'This is where the body content goes...',
));
// Static method on the entity class
$node = Node::create(array('title' => 'A nice title'));
// The best way
$node = \Drupal::entityTypeManager()->getStorage('node')
->create(array('type' => 'page', 'title' => 'Story about me'));
// Delete a single entity
$entity = \Drupal::entityTypeManager()->getStorage('node')->load(100);
$entity->delete();
// Delete multiple entities at once
\Drupal::entityTypeManager()->getStorage($entity_type)
->delete(array($id1 => $entity1, $id2 => $entity2));
// Accessing field values
$node = \Drupal::entityTypeManager()->getStorage("node")->load(22);
$body_text = $node->body->value;
$body_text = $node->get('body')->value;
$body_array = $node->body->getValue();
// Methods are chainable
$second_tag = $node->field_tags[1]->entity->name->value;
$author_name = $node->uid->entity->name->value;
// Retrive referenced entities
$tags = $node->field_tags->referencedEntities();
// The most verbose way
$string = $entity->get('image')->offsetGet(0)->get('alt')->getValue();
// A little bit of magic added by the Entity API
$string = $entity->image[0]->alt;
// More magic - to fetch the first item
$string = $entity->image->alt;
// Get translation
$translation = $node->getTranslation('es');
// English version
print $node->title->value;
// Spanish version
print $translation->title->value;
// Get ids of your entities ...
$query = \Drupal::entityQuery('node')
->condition('status', 1)
->condition('changed', REQUEST_TIME, '<')
->condition('title', 'cat', 'CONTAINS')
->condition('field_tags.entity.name', 'cats');
$nids = $query->execute();
// ... Than load them
$node_storage = \Drupal::entityManager()->getStorage('node');
$nodes = $node_storage->loadMultiple($nids);
$query = Drupal::entityQueryAggregate('node')
->groupBy('type')
->aggregate('nid', 'COUNT');
$result = $query->execute();
// Result is array
// #1 "article" "158"
// #2 "page" "297"