Entity Malformed Exception with field_attach_load() in Drupal 7

While using field_attach_load() to add not loaded fields to a node object, I found myself stubling across that particular error multiple times :

Entity Malformed Exception : Missing bundle property on entity of type node

After spending hours trying to understand what was going on, twice, I decided that publishing the solution of this problem might be a good idea.

The issue generaly comes from the structure of the $entities array passed to field_attach_load(). Here's a good rule of thumb to easily get you out of trouble :

Before passing $entities to field_attach_load(), make sure that :

  • The array is keyed by entity ID,
  • Each array item has at least those 2 keys/values :
    • "type", with the entity bundle as value ("node" in our case),
    • "nid", with the entity ID as value (change the key to "tid" in case of a taxonomy term or "uid" for a user entity).

After that, the error should disappear and never bother you again!