This is very similar to this question: How do I get entity_type and entity_id from any entity page?
But I don't know what that asker means by "Entity Page," and in my case, using debug_backtrace
(seriously?) doesn't cut it as I'd like this function to actually work from more than 1 scope.
Anyway... I am writing a module that uses numerous Entity Reference fields, and works the same code over several types of entities. The trouble is that in my function scope I don't know the type of entity.
If I pass an Entity object into a function, I can access its type parameter:
function foo ($entity) {
// bundle is:
$entity->type;
}
But how do I get the "Entity Type" from this object?
For example, I have a dateset
entity type with several bundles: class
and retreat
. When I pass an instance of the class
bundle into my function, I can identify that it's a class
, and use identifier()
to get its ID. But I want my function foo()
to also handle node
entity types with bundles content_type_a
and content_type_b
Given any instance of one of those bundles, foo()
can identify the bundle:
function foo ($entity) {
$entity->type; // class, retreat, content_type_a or content_type_b
$entity->indentifier(); // numeric ID
}
But what about getting node
vs. dateset
? Doesn't $entity
know what type of entity it is?
UPDATE: Even though I accepted Yury's answer because it provided a realistic workaround, I think the true answer is that you cannot do this in Drupal. You have to pass around $entity_type anywhere you pass $entity (which really kind of makes the idea of having Entities as objects pretty much worthless... but I think any Drupal developer knows that object oriented concepts in Drupal are just hacked in and not ever truly related to real world object oriented design). See this Drupal issue: http://drupal.org/node/1042822