Working With Entity Objects

Entities are objects, so you have to use their methods to retrieve any data from them. Most have some standard methods, and then there will be methods unique to the entity in question.

<?php

/* Examples with a User entity */

$id = $user -> id(); /* Standard method for all entities */

$account = $user -> getAccountName();
$email = $user -> getEmail();
$boolean = $user -> hasPermission('permission id');
$boolean = $user -> hasRole('role id');

/* Examples with a NodeType entity */

$name = $nodeType -> getName();
$description = $nodeType -> getDescription();

/* Examples with a Node entity */

$title = $node -> getTitle();
$type = $node -> getType();

/* To get field data from a node, use the generic get() method with the
   field name, chained with the getValue() method */

$field_sample = $node -> get('field_sample') -> getValue();

/* This will give you an array of values, since fields can be configured to
   accept multiple values.  Even a single value field has its data returned as
   an array.  So, in most cases, you'll just want position zero (0) unless you
   know there are multiple values that you want to iterate over) */

$value = $field_sample[0];

/* You can chain the array reference as well, like so: */

$sample = $node -> get('field_sample') -> getValue()[0];

/* Do note that some fields hold entity references.  In that case, what you
   get back is an array with a key "target_id".  You'll have to use that key's
   value to retrieve the entity if you want to do something with it.  An
   example of this is working with images, like so: */

$image = $node -> field_image -> getValue()[0];
$file = \Drupal\file\Entity\File::load($image['target_id']);
$render['image'] = array(
   '#theme' => 'image',
   '#uri' => $file -> getFileUri(),
);


For more information on render arrays, see the Render Arrays and Twig section of the cookbook.