Skip to main content

How to code Entity/Node/Account Fields ? get, set and create

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 each:

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

Modifying an entity reference multiple fields:

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

Adding new values to the entity 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.

 

Access user fields

// Load the current user.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// Get field data from that user.
$website = $user->get('field_website')->value;
$body = $user->get('body')->value;

// Some default getters include.
$email = $user->get('mail')->value;
$name = $user->get('name')->value;
$uid= $user->get('uid')->value;