Drupal - How do I access a field value for an entity (e.g. node) object?

I guess you do not need to convert $entity into an array, this would simply work.

$entity->get('field_name')->getValue();

FYI : Using kint() from the devel_kint module will let you know all the available methods that could be used to access the object elements, so comparatively var_dump() is less helpful.


in drupal 8 , $node being of class node

 $node->field_machine_name->getValue();

or

$node->get('field_machine_name')->getValue();

will return an array of values.

If you expect only one, you might as well stringify the array with

$node->field_machine_name->getString();

or

 $node->get('field_machine_name')->getString();

For fields you should be able to use $node->body->value for example. If you don't know what the field names are I recommend installing the Devel module for Drupal 8 and inspecting the node via like dsm($node).

Tags:

Entities

8