Extra Block Types (EBT) - New Layout Builder experience❗

Extra Block Types (EBT) - styled, customizable block types: Slideshows, Tabs, Cards, Accordions and many others. Built-in settings for background, DOM Box, javascript plugins. Experience the future of layout building today.

Demo EBT modules Download EBT modules

❗Extra Paragraph Types (EPT) - New Paragraphs experience

Extra Paragraph Types (EPT) - analogical paragraph based set of modules.

Demo EPT modules Download EPT modules

Scroll

9.11.1. Working with Entity fields programmatically

03/10/2019, by Ivan

Retrieving field values in entities is fairly simple, but there are several ways to do this. Let's see how best to work with field values in custom code. You can always see the latest information on working with fields on the official website:

https://www.drupal.org/docs/8/api/entity-api/working-with-the-entity-api

In this article, we will look at examples of working with values. 

You don't have to remember how certain fields work, you can always return to this page and remember. Over time, you will increasingly turn to documentation and realize how easy it is to work with fields in Drupal. In the meantime, you can bookmark this page to always have a cheat sheet on hand.

Working with nodes

Load node by nid:

$nid = 234; 
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$node = $node_storage->load($nid);

Get node id:

$node->id();

Get node/entity bundle:

$node->bundle();   
$entity->getType(); 

Get field values:

$node->get('title')->value;           
$node->get('created')->value;      
$node->get('body')->value;          
$node->get('body')->summary;         
$node->get('field_foo')->value;     
$node->get('field_image')->target_id;

You can also use a short entry to get the values:

$node->title->value;
$node->created->value;
$node->body->value;
$node->body->summary;
$node->field_foo->value;
$node->field_image->target_id;

Loading specific nodes by field value:

$query = \Drupal::entityQuery('node')
  ->condition('type', 'article'),
  ->condition('field_terms', 42);
$nids = $query->execute();
$nodes = $node_storage->loadMultiple($nids);
  
foreach ($nodes as $node) {
  print $node->title->value;
  $node->set('title', "New title for node");
  $node->save();
}

Change the values in the fields:

$node->set('title', "New title");
$node->set('body', array(
'summary' => "Teaser",
'value' => "Long text",
'format' => 'basic_html',
));
$node->save();

Also for fields with a single value, you can use a short entry:

$node->title = 'New title';
$node->field_text = 'text';

Getting the values of multiple fields:

$nids = \Drupal::entityQuery('node')->condition('type', 'album')->execute();
$nodes = Node::loadMultiple($nids);
 
$data = array();
foreach($nodes as $node) {
  $photo = array();
  foreach($node->get('field_image')->getValue() as $file){
    $fid = $file['target_id']; // get file fid;
    $photo[] = \Drupal\file\Entity\File::load($fid)->getFileUri();
  }
 
  $data[] = array(
    'album_name' => $node->get('field_album_name')->getValue(),
    'place' => $node->get('field_place')->getValue(),
    'author' => $node->get('field_author')->getValue(),
    'photo' => $photo,
  );
}

Working with file fields

Files are added to other entities via reference fields, and when we access these fields, we can get the file ID and then get the file information from the ID.

Getting a file by ID:

$fid = 42; 
$file_storage = \Drupal::entityTypeManager()->getStorage('file');
$file = $file_storage->load($fid);

Getting the file object from the node field:

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

Getting some fields of a file object:

$file->getFileUri();   // "public://file123.jpg"
// You can transform to file URL from URI: file_url_transform_relative(file_create_url($file->getFileUri()));   
// "/sites/default/files/public/file123.jpg"
$file->filename->value;   // "file123.jpg"
$file->filemime->value;   // "image/jpeg"
$file->filesize->value;   // 63518  (size in bytes)
$file->created->value;    // 1511206249  (Unix timestamp)
$file->changed->value;    // 1511234256  (Unix timestamp)
$file->id();

You can view the file property values available from the file_managed table as follows:

echo $file->uid->target_id;               // 1
echo $file->uid->value;                   // It doesn't work! Use target_id.
echo $file->uid->entity->name->value;    
echo $file->uid->entity->timezone->value; // "Asia/Omsk"

Working with Entity Reference Fields

You can get multiple values from reference fields and process them through foreach:

foreach ($node->field_my_entity_reference as $reference) {  
  print $reference->target_id;  
  print $reference->entity->title->value;  
}

Modifying an entity reference multiple field:

$nids = [3,4,5,6];  
$node->set('field_my_entity_reference', $nids);
$node->save();

Adding new values to the enitty reference field to existing values:

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

Working with paragraphs

$my_paragraph = null;
  
foreach ($node->get('field_paragraph_reference') as $paragraph) {
  if ($paragraph->entity->getType() == 'your_paragraph_type') {  
    $my_paragraph = $paragraph->entity;
  }
}
  
if (!empty($my_paragraph)) {
  print $my_paragraph->field_somefield->value;
  
  print $my_paragraph->title->value;  // It doesn't work!
} 
else {
  print "The node doesn't have this paragraph type.";
}

Getting the type of paragraph:

$my_paragraph->getType();

We will use these examples in the future to write custom modules working with hooks and entity objects.