“Explore methods and examples for efficient programmatic manipulation of entity fields in Drupal, enhancing development flexibility and control.”
1. Working with Nodes:
Loading Node by NID:
$nid = 234;
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$node = $node_storage->load($nid);- $nid = 234;: A variable ($nid) is assigned the value 234, representing the node ID you want to work with.
- $node_storage = \Drupal::entityTypeManager()->getStorage('node');: The EntityTypeManager is used to retrieve the storage handler for the 'node' entity type. This handler is responsible for loading, saving, and managing node entities.
- $node = $node_storage->load($nid);: The load method is invoked on the node storage handler, loading the node with the specified ID ($nid). The resulting node entity is then stored in the variable $node for further manipulation or processing in your Drupal code.
Getting Node ID and Bundle:
$node->id();
$node->bundle();
// or
$node->getType(); - $node->id(); retrieves the unique identifier (ID) of the Drupal node object, representing a specific content item in the system.
- $node->bundle(); or $node->getType(); fetches the content type (bundle) associated with the Drupal node. Both methods return the machine name of the content type. Using either bundle() or getType() achieves the same result.
Getting 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;
// Short entries
$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();
}- Entity Query:
- $query = \Drupal::entityQuery('node'): Initiates an entity query for nodes.
- ->condition('type', 'article'): Adds a condition to filter nodes by type, selecting only those of type 'article'.
- ->condition('field_terms', 42): Adds another condition to filter nodes by the value of the 'field_terms' field being equal to 42.
- Execute Query and Load Nodes:
- $nids = $query->execute(): Executes the query and retrieves an array of node IDs that match the specified conditions.
- $nodes = $node_storage->loadMultiple($nids): Loads multiple nodes using the node storage service based on the obtained node IDs.
- Node Iteration:
- foreach ($nodes as $node): Iterates through the loaded nodes.
- Output Node Title:
- print $node->title->value: Prints the current node's title value.
- Update and Save Node Title:
- $node->set('title', "New title for node"): Sets a new title for the node.
- $node->save(): Saves the updated node with the new title.
In summary, this code retrieves nodes of type 'article' with a specific value in the 'field_terms' field, iterates through them, prints their current titles, updates each node's title to "New title for node," and saves the changes back to the database.
Changing Field Values:
$node->set('title', "New title");
$node->set('body', array(
'summary' => "Teaser",
'value' => "Long text",
'format' => 'basic_html',
));
$node->save();
// Short entry for fields with a single value
$node->title = 'New title';
$node->field_text = 'text';Getting Values of Multiple Fields:
$nids = \Drupal::entityQuery('node')->condition('type', 'album')->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
$data = array();
foreach ($nodes as $node) {
$photo = array();
foreach ($node->get('field_image')->getValue() as $file) {
$fid = $file['target_id'];
$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,
);
}2. Working with File Fields:
Getting a File by ID:
$fid = 42;
$file_storage = \Drupal::entityTypeManager()->getStorage('file');
$file = $file_storage->load($fid);Getting File Object from Node Field:
$file = $node->field_image->entity;Getting File Field Values:
$file->getFileUri(); // "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();Viewing Additional File Properties:
echo $file->uid->target_id; // 1
echo $file->uid->entity->name->value;
echo $file->uid->entity->timezone->value; // "Asia/Omsk"3. Working with Entity Reference Fields:
Getting Values from Reference Fields:
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 Entity Reference Field:
$nids = [3,4,5,6];
foreach ($nids as $nid) {
$node->field_my_entity_reference[] = [
'target_id' => $nid
];
}
$node->save();4. 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;
// It doesn't work!
// print $my_paragraph->title->value;
}
else {
print "The node doesn't have this paragraph type.";
}Getting Paragraph Type:
$my_paragraph->getType();
These examples cover various aspects of working with fields, nodes, files, entity reference fields, and paragraphs in Drupal 9. Adjust the code based on your specific requirements and use cases. Always refer to the official Drupal documentation for the latest information on working with the Entity API.
