Skip to content

Instantly share code, notes, and snippets.

@levmyshkin
Created November 19, 2021 13:58
Show Gist options
  • Save levmyshkin/9225018a12b8d198920fc9dbebe7262b to your computer and use it in GitHub Desktop.
Save levmyshkin/9225018a12b8d198920fc9dbebe7262b to your computer and use it in GitHub Desktop.
Drupal Working with node fields programmatically
<?php
// Load node by nid:
$nid = 234;
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$node = $node_storage->load($nid);
// Get node id:
$nid = $node->id();
// Get node/entity bundle:
$bundle = $node->bundle();
$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,
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment