Drupal Cheat Sheet - Accessing Node fields programatically

Note Statistics

Note Statistics

  • Viewed 32 times
Sat, 07/24/2021 - 18:30

Accessing properties

The convention below can be used to access all node properties.


$node->get(<properyname>)-><subproperty>;  
 
 // or 
 
$node->property_name->getValue()['<subproperty>'];  


$node->get('title')->value;  
$node->get('created')->value;     
$node->get('body')->value;    
$node->get('body')->summary; 
// a custom text field
$node->get('field_text)->value;  
$node->field_text->getValue();  
// reference field
$node->field_related_node->getValue()[0]['target_id'];  
// a file field
$node->get('field_image')->target_id; 

Now there are wrapper methods in node that you can use.

Get Node's ID


$node->id();  // 1234

Get node's bundle/type


$node->bundle();    // 'article'
$node->getType();

Get node's title


$node->getTitle();   
$node->get('title')->value;

Check if the node is promoted


$node->isPromoted()

Check if the node is sticky


$node->isSticky()

Authored by