2

My content type "Export" has an entity reference to the type "country" (i.e. you assign countries to the export). I wish to do something like the following

$countries = $node->field_exporter_countries['und'][0]['value'];

foreach ($countries as &$value) {
   print $value;
}

Edit

I also tried this. But i get the wrong titles back.

$nodes = entity_load('node', array_keys($countries));
foreach ($nodes as $n) {
  print $n->title;
  print "<br /> ";
}
3

According to the entityreference_field_schema() function, the column name for an entity reference field is target_id (not value). That said, to extract the node ids you should probably use something like this:

$nids = array();
foreach ($node->field_exporter_countries[$node->language] as $index => $item) {
  $nids[] = $item['target_id'];
}

$nodes = entity_load('node', $nids);

// etc...
2

I don't have Drupal in front of me at the moment so this is pure guestimation, but I think you're actually looking at doing something like the following:

$countries = $node->field_exporter_countries[$node->language];

foreach ($countries as $key => $data) {
  print $data['value'];
}

Note that I've used $node->language instead of und as a personal preference, but there are other benefits.

  • thanks, i tried you loop but i get not results. I also tried to cast it to node but i get the wrong drupal pages. See above – frosty Apr 17 '12 at 18:01
  • to clarify. if i go count($countries) i get results. So there is data there. – frosty Apr 17 '12 at 18:10
0

Generally if you have a field, and you want to format its output a certain way, you implement a field formatter.

And if you do implement a new field formatter, Drupal will call hook_field_formatter_view() for you, with $items as a handy array to turn into a renderable array.

  • I don't think the OP ever mentioned displaying fields. A field formatter would be relatively useless if you want to manipulate the data in code. – Chapabu Apr 10 '12 at 20:47
  • 1
    It does kinda say "print($value);" doesn't it? :-) – paul-m Apr 11 '12 at 5:48

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.