Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Drupal entity API cheat sheet

Parent Feed: 

As I've explained Short trip on Entity API in Drupal 8  Entity is the most important thing in Drupal 8, Almost, everything is Entity. So for a Drupal developer, it should be good to have a cheat sheet of Entity API instead of googling every time he/she need something, and of course, after a while, they saved in the long-term memory of Developer.

Let's jump into summarized Drupal 8 Entity API.

Working with nodes

Load a node by NID:

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

Get node's bundle (content) type:

echo $node->bundle();    // return bundle ( content) type on node with nid=66 in my sample, it's a page
echo $node->getType();    // 'article' - this is the same as bundle() for most entities, but doesn't work for all entity types

Get a built-in field value:

echo $node->get('title')->value;           // "Lorem Ipsum..."
echo $node->get('created')->value;         // 1518923456
echo $node->get('body')->value;            // "The full node body, <strong>with HTML</strong>"
echo $node->get('body')->summary;          // "This is the summary"
// a custom text field
echo $node->get('field_foo')->value;       // "whatever is in your custom field"
// a file field
echo $node->get('field_image')->target_id; // 101 (a managed file FID)

Get a built-in field value (the shorthand, with getters):

echo $node->title->value;            // "Lorem Ipsum..."
echo $node->created->value;          //1518923456
echo $node->body->value;             // "This is the full node body, <strong>with HTML</strong>"
echo $node->body->summary;           // "This is the summary"
echo $node->field_foo->value;        // "whatever is in your custom field"
echo $node->field_image->target_id;  // 101

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', "Hello Wrold test Title");
  $n->save();
}

How to Set fields values with Drupal Entity API :

$node->set('title', "Zhilevan is Happy Today");
$node->set('body', array(
'summary' => "Today I'm happy because of nice weather",
'value' => "Today I'm happy because of nice weather.thanks god",
'format' => 'basic_html',
));
$node->save();

 

How to delete Drupal Nodes with API:

// one
$nid = 66;      // example value
$node = $node_storage->load($nid);
$node->delete();
 
// multiple
$nids = [1,14,55,68];  // example value
$nodes = $node_storage->loadMultiple($nids);
$node_storage->delete($nodes);
 
// multiple, loading one at a time to avoid "out of memory" errors - may be slow
$nids = [1,14,55,68];  // example value
foreach($nids as $nid)
{
  $node = $node_storage->load($nid);
  $node->delete();
}

Working with Other Entities in Drupal 8( Paragraphs , Files, Users )

OK. that's enough for Nodes, let's jump into the entity_ref fields, like Paragraph. Of course, Field Collection was one of the important modules in Drupal 7 and has a significant role in Drupal websites but because of some big issues about memory-hungry and structural, it's almost dead in Drupal 8 and Paragraph module is a new Hero in Drupal 8.lets have a journey in working with Paragraph ( and other entity ref fields ) with Entity API 

Working with Paragraphs

$my_paragraph = null;
 
foreach ($node->get('field_paragraph_reference') as $para) {
  if ($para->entity->getType() == 'your_paragraph_type') {   // e.g., "main_content" or "social_media"
    $my_paragraph = $para->entity;
  }
}
 
if (!empty($my_paragraph)) {
  // $my_paragraph is a regular entity and can be interacted with like any other entity
  echo $my_paragraph->field_somefield->value;
 
  // (however, they don't have a "title" like a node)
  echo $my_paragraph->title->value;  // <-- this won't work
} else {
  echo "The node doesn't have this paragraph type.";
}

How to get paragraph entity type:

echo $my_paragraph->getType(); // "main_content"

Working with File entities

Managed files are also separate entities, which are associated with the node using a type of Entity Reference.

How to get a file by ID in Drupal:

$fid = 31;      // example value
$file_storage = \Drupal::entityTypeManager()->getStorage('file');
$file = $file_storage->load($fid);

Get a file referenced in a node:

$file = $node->field_image->entity;

Reading some properties from a File entity:

echo $file->getFileUri();   // "public://filetest.jpg"
// if you want the URL without Drupal's custom scheme, you can translate it to a plain URL:
echo file_url_transform_relative(file_create_url($file->getFileUri()));   // "/sites/default/files/public/filetest.jpg"
echo $file->filename->value;   // "filetest.jpg"
echo $file->filemime->value;   // "image/jpeg"
echo $file->filesize->value;   // 63619  (size in bytes)
echo $file->created->value;    // 1592206249  (Unix timestamp)
echo $file->changed->value;    // 1592234256  (Unix timestamp)
echo $file->id();              // 31

Working with User Entity

echo $file->uid->target_id;               // 1
echo $file->uid->entity->name->value;     // "zhilevan"
echo $file->uid->entity->timezone->value; // "Asia/Tehran"

Working with Entity References ( like Taxonomy Terms, etc)

foreach ($node->field_my_entity_reference as $reference) {
 
  // if you chose "Entity ID" as the display mode for the entity reference field,
  // the target_id is the ONLY value you will have access to
  echo $reference->target_id;    // 1 (a node's nid)
 
  // if you chose "Rendered Entity" as the display mode, you'll be able to 
  // access the rest of the node's data.
  echo $reference->entity->title->value;    // "Zhilevan Ibra"
 
}

Changing  the value(s) of an entity reference field is much easier than Drupal 7 :

$nids = [1,2,3,4];   // example value
$node->set('field_my_entity_reference', $nids);
$node->save();

Or appending 

$nids = [5,6];   // example value
foreach ($nids as $nid) {
  $node->field_my_entity_reference[] = [
    'target_id' => $nid
  ];
}
$node->save();

much easier than Drupal 7, isn't? 

Enjoy your coding and share your comments with me ;-)

References:

 Working with the Entity API on Drupal.org

The Ultimate Guide to Drupal 8 - Drupal Groups

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web