Ted Bowman's picture

Ever wonder how to find the entity_id of any enity in Drupal 7.  Of course for most common entity types it is very simple. $node->nid for nodes, $user->uid for users, etc. But what if you want to simplify your code to avoid code like this:

switch($entity_type){

 case 'node':    $entity_id = $entity->nid;   case 'user':     $entity_id = $entity->user;   .... }

 

Also what if you want to handle entity types that you don't know about before hand.  I ran into this problem recently when I wanted to write a patch for the Scheduled actions (D7) module.  I needed to delete all scheduled actions for an entity in an implementation of hook_entity_delete.  

Luckily Drupal has the function entity_extract_ids which will give you the primary id, version id and bundle name for any entity.  You need the entity type and the entity object.  It returns you:

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 to get the entity_id of any entity you just use:

$entity_id = array_shift(entity_extract_ids($entity_type,$entity));

Voilà, works for any entity!!

Feeds: 

Comments

Concise and useful article! Thank you, it help me a lot for solving a problem in my coding.

Ted Bowman's picture

Glad you found it useful!

Add new comment

Online Trainings

Six Mile Tech offers online trainings via Skype, Google Hangout, or a screen sharing technology of your choice. These trainings can be used for generalized Drupal trainings or to tackle a specific problem for a site you are working on.