I need to identify bundle
of an entity from its type
and id
.
For example, if the type
is 'node' and id
is 7, I may get 'page' as bundle
.
Thanks
Use entity_load
to load the entity as mentioned by @Nikhil.
Then use entity_extract_ids, to extract the bundle. Example:
$entity = entity_load('node', array('7'));
list(, , $bundle) = entity_extract_ids('node', $entity);
echo "Bundle name is : " . $bundle;
The function entity_extract_ids
returns a numerically indexed array (not a hash table) containing the elements:
where, 0
, 1
, and 2
are array indices. However, the approach used by core and contrib modules is to use the list()
function.
list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
Here is the cleanest one that I got from Organic groups module code.
$wrapper = entity_metadata_wrapper($entity_type, $entity_id);
$bundle = $wrapper->getBundle();
For example I can call it like:
$wrapper = entity_metadata_wrapper('node', 1);
$bundle = $wrapper->getBundle();
Edit: As @Clive pointed out, above method depends on entity module.
Here is another method that does not depend on any extra module. It is explained here https://forrst.com/posts/Get_the_bundle_of_a_Drupal_7_entity-0xW
Copy pasting that method:
function _entity_get_bundle($entity, $entity_type) {
$info = entity_get_info($entity_type);
if (empty($info['entity keys']['bundle'])) {
return $entity_type;
} else {
return $entity->{$info['entity keys']['bundle']};
}
}
$group_type, $gid
? and whats the value in $bundle
?
entity_load
, by the way how its cleanest ?
entity_metadata_wrapper()
is cleaner than the entity_extract_ids()
method. Plus you rely on the entity module being installed...
Try entity_load
Load entities from the database.
The entities are stored in a static memory cache, and will not require database access if loaded again during the same page request.
$entity_type: The entity type to load, e.g. node or user.
$ids: An array of entity IDs, or FALSE to load all entities.
$conditions: (deprecated) An associative array of conditions on the base table, where the keys are the database fields and the values are the values those fields must have. Instead, it is preferable to use EntityFieldQuery to retrieve a list of entity IDs loadable by this function.
$reset: Whether to reset the internal cache for the requested entity type.
An array of entity objects indexed by their ids. When no results are found, an empty array is returned.
If you want a very lightweight way, performance-wise, to get the node type from node id - you can use a single select query on the node table.
$type = db_query("SELECT type FROM {node} WHERE nid = :nid",
array(':nid' => $nid))->fetchField();
That way, you don't need to invoke the entire entity hook system, with entity_load etc..
It's a single select query using the indexed node id.