Get Your IDEntity or How To Get Entity Id In Drupal 7?

13 Sep ยท by Tim Kamanin ยท 2 min read

Drupal 7 (and, obviously Drupal 8) breathe by entity. Entities are everywhere and you can't code a site without them. But here is the problem: all entities have ids, but these ids have different names accross Drupal. Just to give you few examples: Entity id in Node is $node->nid, Entity id in User is $user->uid and so on. Inconsistency as you may say. What if you want to write a code which works accross all entities, how to get entity id for every entity type without writing additional code? I'll show you how.

The answer is Drupal API and entity_extract_ids($entity_type, $entity) function. This is a helper function to extract id, vid, and bundle name from an entity. It accepts two parameters: $entity_type , which can be a text value of 'node', 'user' or whatever type of an entity and $entity which is an entity object itself (for example, $node, $user). Function returns a numerically indexed array (not a hash table) containing these elements: 0: primary id of the entity, 1: revision id of the entity, or NULL if $entity_type is not versioned, 2: bundle name of the entity.

So for example, if we have a code which should work for $node and $user entities, we can get their entity_ids in a very standard way:

case 1:

$entity_ids = entity_extract_ids('node', $node);
$entity_id = $entity_ids[0];

case 2:

$entity_ids = entity_extract_ids('user', $user);
$entity_id = $entity_ids[0];

Where this function can be useful? I myself find this approach useful in situations like function hook_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items), where hook provides you with $entity_type and $entity object and where you need to get $entity object id to manipulate the data, but object can be of a variable type (it can be node, user, other entity) because fields should work with any entity type.

Want to get more ๐Ÿ”ฅ tips like this one?

Subscribe to get notified about new dev tutorials