
Best ways to get node field values programmatically in Drupal 11 using Entity API, Typed Data API, and modern PHP techniques.
As a Drupal 11 developer, efficiently retrieving node field values is a fundamental skill for building custom modules, themes, and migrations. Drupal 11 continues to enhance its Entity API and Typed Data API, making field value retrieval more intuitive and powerful than ever.
Method 1: Simple Field Value Access with
$node = \Drupal\node\Entity\Node::load($nid);
// For simple text/number fields
$title = $node->get('title')->value;
$integer_field = $node->get('field_integer')->value; Method 2: Accessing Complex Field Data with getValue()
$node = Node::load($nid);
// For formatted text (body)
$body_data = $node->get('body')->getValue()[0];
$text = $body_data['value'];
$summary = $body_data['summary'];
$format = $body_data['format'];
// For date fields
$date_data = $node->get('field_date')->getValue()[0];
$timestamp = strtotime($date_data['value']); Method 3: Modern Entity Reference Handling
$node = Node::load($nid);
// Single reference
$referenced_node = $node->get('field_article')->entity;
if ($referenced_node) {
$title = $referenced_node->label();
}
// Multiple references
foreach ($node->get('field_tags')->referencedEntities() as $term) {
$term_names[] = $term->label();
} 
Pro Tip: Bookmark the Drupal 11 Entity API documentation for the latest updates!

0 Comments