In modern Drupal development, interacting with entities—whether they are nodes, users, taxonomy terms, or custom blocks—is an essential skill. Since the release of Drupal 8 and continuing through Drupal 10 and 11, the way we interact with data has shifted from simple associative arrays to a sophisticated, object-oriented Entity API.
If you are coming from a background of procedural code, you might find the transition to objects slightly daunting. However, once you understand the patterns for accessing field values, you will find the system much more predictable and powerful. This guide will walk you through the various methods of retrieving data from an entity object, from simple text strings to complex entity references.
Loading the Entity Object
Before you can access a field value, you must first have the entity object in hand. In a controller or a hook, you might already have a $node or $user object. If you only have the ID (NID or UID), you need to load the entity first.
While you might see legacy code using node_load(), the modern standard is to use the static load() method or the entityTypeManager service.
Using the static method:
use Drupal\node\Entity\Node;
// Load a node by its ID.
$node = Node::load($nid);
If you are inside a service or a controller where dependency injection is available, you should use the entityTypeManager service:
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
If you need to retrieve the current node from the URL route, you can use the route match service:
$nid = \Drupal::routeMatch()->getRawParameter('node');
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
Standard Methods to Access Field Values
Once you have your entity object (let's assume it is a $node), there are several ways to reach the data stored inside its fields.
The Direct Property Access (Magic Methods)
Drupal provides magic methods that allow you to access field values as if they were properties of the object. This is the most readable and common approach for simple fields.
// Accessing a simple text field value
$value = $node->field_machine_name->value;
// Accessing the node title
$title = $node->title->value;
Using the get() Method
The get() method is the formal way to access a field. It returns a field item list, which you can then query for values. This is often safer when the field name is dynamic.
// Using the get() method to retrieve a value
$value = $node->get('field_machine_name')->value;
Retrieving All Values (Arrays)
If a field has multiple values (e.g., a list of tags or multiple text entries), using ->value will only return the first item. To get the full array of data, use getValue().
// Returns an array of all values for the field
$all_values = $node->get('field_machine_name')->getValue();
This will typically return a structure like this:
[
0 => ['value' => 'First Value'],
1 => ['value' => 'Second Value'],
]
Working with Entity Reference Fields
Entity reference fields are a bit unique because they store a link to another entity (like a taxonomy term or another node). You have two main ways to interact with these fields: getting the ID or getting the fully loaded referenced entity.
Getting the Target ID
If you only need the ID of the referenced item (e.g., the TID of a term), use target_id.
// Get the ID of the first referenced entity
$target_id = $node->get('field_category')->target_id;
Loading the Referenced Entity Directly
One of the most powerful features of the Entity API is the ability to "dot-walk" into referenced entities. By using ->entity, Drupal will automatically load the referenced object for you.
// This loads the actual term entity from the field
$referenced_entity = $node->get('field_category')->entity;
// Now you can access values on THAT entity
if ($referenced_entity) {
$term_name = $referenced_entity->label();
}
Handling Multiple References
If your field allows multiple references, use the referencedEntities() method to get an array of loaded objects.
$entities = $node->get('field_tags')->referencedEntities();
foreach ($entities as $entity) {
// Process each term or node
$name = $entity->label();
}
Advanced Retrieval and String Formatting
Sometimes you don't want the raw value stored in the database; you want a string representation of the field. This is particularly useful for fields that contain complex data.
Using getString()
The getString() method provides a comma-separated string representation of the field's values. It is a quick way to get a human-readable version of the data.
// Useful for quick display or logging
$summary = $node->get('field_tags')->getString();
The toArray() Method for Debugging
If you are struggling to find where a specific value is hidden within a complex entity, the toArray() method is your best friend. It converts the entire entity object into a nested associative array, making it much easier to inspect with standard PHP tools.
// Convert the whole node to an array for inspection
$node_array = $node->toArray();
print_r($node_array);
Debugging Your Entities
While print_r() and var_dump() are available, they are often overwhelming when used on Drupal entity objects due to the deep recursion and dependency injection containers.
To debug effectively, it is highly recommended to install the Devel module. Once enabled, you can use kint() or dsm() to inspect your objects:
// If using Devel and Kint
ksm($node);
// Or inspect just the values
ksm($node->toArray());
If you are using Xdebug with an IDE like PhpStorm, you can set a breakpoint and inspect the object directly. However, even with Xdebug, the toArray() method remains a cleaner way to see the raw data structure without the internal object overhead.
Frequently Asked Questions
How do I get the node title or ID without using fields?
While you can use $node->get('title')->value, entities have built-in helper methods for common properties. Use $node->id() to get the entity ID and $node->label() (or $node->getTitle() specifically for nodes) to get the title.
Why does $node->field_name->value return NULL?
This usually happens if the field is empty or if the field name is misspelled. Always ensure you are using the machine name of the field. It is also good practice to check if the field exists using $node->hasField('field_name') or if it is empty with $node->get('field_name')->isEmpty().
What is the difference between value and target_id?
The value property is used for standard data types like strings, integers, and booleans. The target_id property is used specifically for entity reference fields to store the numeric ID of the linked entity.
Wrapping Up
Accessing field values in Drupal is a multi-layered process that offers flexibility depending on your needs. For simple scripts, the magic property access $node->field_name->value is perfect. For more robust application logic, using get() and referencedEntities() ensures you are working correctly with Drupal's Typed Data API.
By mastering these retrieval patterns, you can write cleaner, more maintainable code and spend less time fighting with data structures. Always remember to use tools like Devel or Xdebug to verify the structure of your entities as you build.