1

I'm using an EntityFieldQuery to load a node and try to access some of its fields, but can't seem to get any of the fields. The code is below:

$nodestoload = $query->execute();
$nids = array_keys($nodestoload['node']);
$nodes = entity_load('node', $nids);
print_r($nodes);
$output = field_view_field('node', $nodes, 'suppliername');

However, $output is returning an empty array. I can see that the node loads using the print_r. I've also tried various options (such as replacing 'node' with the actual bundle type). But nothing seems to be working... How do I access fields from a node that I loaded programmatically?

4
  • Names for fields added through the UI are prefixed with field_, any chance that's the problem?
    – Clive
    Commented Feb 10, 2013 at 3:12
  • When I try that I get a "EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids" error??
    – RedRaven
    Commented Feb 10, 2013 at 3:13
  • 1
    field_view_field() is for a single value, you just need to loop over $nodes...
    – Clive
    Commented Feb 10, 2013 at 3:14
  • Seems to have worked, thanks. Want to put it as the answer?
    – RedRaven
    Commented Feb 10, 2013 at 4:12

2 Answers 2

1

The correct code is the following one.

$nodes_to_load = $query->execute();
if (isset($nodes_to_load['node'])) {
  $nodes = entity_load('node', array_keys($nodes_to_load['node']));

  foreach ($nodes as $node) {
    $output = field_view_field('node', $node, 'suppliername');
    // ...
  }
}

field_view_field() accepts a single entity object, as second argument; you cannot pass it an array of entities.

1

Your code will only work if there is only a single value returned by your EFQ. Whatever you want to do with the nodes, you need to put in a foreach():

$nodestoload = $query->execute();
foreach ($nodestoload as $loaded_node) {
  $nid = array_keys($loaded_node['node']);
  $node = entity_load('node', $nid);
  print_r($node);
  $output = field_view_field('node', $node, 'suppliername');
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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