node_load((int) $nid) loads a fully-populated node entity.
$node->title->value gets the title, but how do I access field values in Drupal 8?
I guess you do not need to convert
$entity into an array,
this would simply work.
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
will return an array of values.
If you expect only one, you might as well stringify the array with
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
You can always do
$entity->toArray() to see what's in an entity. Even when using xdebug (for example with phpstorm) making sense of an entity object on its own is very hard. I doubt
dsm($node) in Drupal 8 makes any sense. If you insist on in-browser debugging (but you shouldn't, Drupal 8 is too complex to debug without xdebug)
dsm($node->toArray()) is what you want.
Use following code snippet to get node field values
This is used to get node id from url
$nid = \Drupal::routeMatch()->getRawParameter($node_id);
To load node data using nid
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
This is used to get field value.
$terms = $node->get('field_Name')->getValue();
This is used to get node title.
$product_name = $node->getTitle();
use Drupal\node\Entity\Node $node = Node::load($nid); $title = $node->get('title')->value;
use Drupal\node\Entity\Node $title = Node::load($nid)->get('title')->value;
Here is nice write up about accessing values from the node object https://www.frobiovox.com/posts/2016/03/28/simplify-drupal-8-field-value-calls.html
If the field is an entity reference field, there are some special ways to get the referenced entities.
To get the target id (first element):
To get the loaded entity (first element):
->entity on the field it automatically returns the loaded entity.
If the field can contain multiple references, you can fetch them all like this:
$entities = $entity->get('field_entity_reference')->referencedEntities();
That will return an array of entities.