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:


 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!!


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!

Other Services

Drupal Consulting

Need help with project Planning?

Are you lost trying to select modules to implement your sites functionality?

Looking to simplify your Drupal development and solve problems faster?

Are you having trouble with modules such as Views or Panels?

Six Mile Tech’s Drupal consulting provides you or your company with an experienced Drupal expert.  You will be able to eliminate hours or days of wasted time looking for a way to solve your problem in Drupal. We can get you past your current dead ends in Drupal and we can teach you to solve your problems in Drupal the right way.

Contact Us to today to Learn More

Project Mentoring

Our mentoring service provides you with guidance through all of the phases of your Drupal project from planning to deployment.  We can help make sure that you are making your Drupal website the right way from the start.  With our guidance you will avoid common costly mistakes and start making more for your time.

Contact Us to today to Learn More


Training Newsletter

Sign up for our Training Newsletter to hear about in person and online trainings as well as to receive exclusive discount codes.

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.