4

I've got a field collection attached to a node. Given the entity ID of a given instance of that collection, how do I obtain the nid to which it's associated?

When using entity_load, the nid for some reason is a protected property, so I can't access it. I must be missing something.

Update: using node_load on this entity ID returns false.

5
  • If you use node_load() instead of entity_load() you should be able to access it. Any particular reason why you are using entity_load()? Dec 12 '11 at 18:37
  • I had no idea you could use node_load(). Nice! I will try this.
    – Justin
    Dec 15 '11 at 15:57
  • I don't see it in the node_load() object. What am I looking for?
    – Justin
    Dec 15 '11 at 16:01
  • node_load() takes the nid as the argument. :-)
    – paul-m
    Jan 15 '12 at 0:20
  • Guys, I know how node_load works. It returns false when I give it this entity ID (which is for a field collection).
    – Justin
    Jan 26 '12 at 15:31
4

It's important to understand that if all you have is the id of any entity, then there is no way to load a specific entity with that id. Since entity_id's are not unique across entity-types, it is necessary to know both the entity type, and the entity id.

See Developers need an $entity->entity_type property for a discussion on changing this for D7, as well as info about how this will be likely be handled in D8.

On the other hand, as pointed out in a different answer, if you already know that the entity id is a node id, then you can call an entity specific load function like node_load($nid). Since most entities will have such a load function to support named arguments, such a "shortcut" function will be almost universally available.

Examples: node_load(), taxonomy_term_load(), commerce_product_load().

3

In this example Classroom is a content type (entity) with a field called field_students. field_students is a node reference field, and it references nodes (entities) of content type Student.

// Get all the Student items attached to a field. 
$studets = field_get_items('node', $classroom, 'field_students');

// Get the node id of the Student entity in the first field entry.
$student_nid = $studets[0]['nid'];

// Create a full object (node) representation of the student.
$student_obj = node_load($student_nid);
1
  • This has nothing to do with a field collection
    – AlxVallejo
    Jan 26 '15 at 17:13

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.