Drupal - How do I get entity_type and entity_id from any entity page?
In Drupal Core, you cannot do this. The relevant issue to add such functionality is here.
What core itself does is always passing around two arguments:
function($entity, $entity_type)
I spotted something that works as this in the module Token Filter (D7 version):
// Attempt to fetch the entity that is being viewed via a backtrace to the
// field_attach_view($entity_type, $entity) function and parameters §if found.
$backtrace = debug_backtrace();
foreach ($backtrace as $caller) {
if ($caller['function'] == 'field_attach_view') {
$entity_type = $caller['args'][0];
$entity = $caller['args'][2];
// do stuff with entity
break;
}
}
Pretty smart - it figures out a function that must have happened before its function is called which will contain $entity_type and $entity ($entity_id would also work instead of $entity), and looks back through the backtrace object until it finds it.
Token Filter is a field processing module, so it will know that its function will always have been called after a call to field_attach_view(). I'm not if there is a good generic alternative to field_attach_view - but the general approach seems to work and a case-specific candidate can always be found for any specific case by dropping some backtrace debug code (formerly broken link fixed) into the point in the code where you need to get the entity, and seeing what's available (then checking logic and testing to make sure it is always present).
The most straightforward way I have found to solve this issue is to implement hook_entity_load()
.
function MODULE_entity_load($entities, $entity_type) {
foreach ($entities as $entity) {
$entity->entity_type = $entity_type;
}
}
Then the object returned by menu_get_object()
will have an entity_type bound to it.