-1

I have a view node and I use the below code to Kint out the node objects:

$node = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadMultiple();
 dpm($node);

returns the below output:

enter image description here

I get to see the properties of each node. In this, I want to access the target_id/value of the highlighted field - field_cp_level2_ref_level3. I tried the below line and it is coming out as null:

$node->field_cp_level2_ref_level3->target_id

How to access this field value?

6
0

Your problem is that you wrongly assume the result of loadMultiple to be a node object, when instead it returns an array of node objects.

You should be able to do this:

$nodes = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadMultiple();
$node = reset($nodes);

You should now be able to access the values you see in your debug output:

$node->field_cp_level2_ref_level3->target_id;

It's actually a bit questionable to load all the nodes you have in your system. That might still work with your 294 nodes, but it will create problems on sites with more content. Instead you should add conditions, e.g. by using loadByProperties on the node storage.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.