0

I have a node with a entity reference field (more precisely a product reference). How do I access the fields of the referenced entity from the node?

(I’m trying to do it through a code field in the Display Suite, so I have access to the $entity object, not sure if that helps)

To explain better I would like to be able to do something like these tokens:

[node:field-products:0:field-flow-rate]
[node:field-products:1:field-flow-rate]
[node:field-products:2:field-flow-rate]

but with PHP, so I can cycle through the index.

2

You can use entity_metadata_wrapper() to easily get referenced entities, their field and much more.

$node_wrapper = entity_metadata_wrapper('node', $entity);

foreach ($node_wrapper->field_products as $product_wrapper) {
  // You can print or do whatever you like with the value of the fields 
  // of the referenced entity like below:
  print $product_wrapper->field_flow_rate->value();
}
| improve this answer | |
1

I'm not sure of the exact structure of your node object (use dpm($node) or print_r($node) if you don't have a debugger). But assuming the entity_ref field is called field_products then you would do something like this:

foreach ($node->field_products as $nid) {
  $child = node_load($nid); // might be $nid[0], use dpm to find out
  $flow_rate = $child->flow_rate;
}
| improve this answer | |

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.