
Upgrade Your Drupal Skills
We trained 1,000+ Drupal Developers over the last decade.
See Advanced Courses NAH, I know EnoughGet Your IDEntity or How To Get Entity Id In Drupal 7?
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.
Tags
About Drupal Sun
Drupal Sun is an Evolving Web project. It allows you to:
- Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
- Facet based on tags, author, or feed
- Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
- View the entire article text inline, or in the context of the site where it was created
See the blog post at Evolving Web