In Drupal 10, an entity object represents content or data like nodes, users, etc. It's fieldable and extensible. Each entity type has bundles, enabling varied configurations. The Entity API facilitates programmatically interacting with entities, offering functions for CRUD operations and querying.
Check the type of entity
// Make sure that an object is an entity.
if ($entity instanceof \Drupal\Core\Entity\EntityInterface) {
}
// Make sure it's a content entity.
if ($entity instanceof \Drupal\Core\Entity\ContentEntityInterface) {
}
// or:
if ($entity->getEntityType()->getGroup() == 'content') {
}
// Get the entity type or the entity type ID.
$entity->getEntityType();
$entity->getEntityTypeId();
// Make sure it's a node.
if ($entity instanceof \Drupal\node\NodeInterface) {
}
// Using entityType() works better when the needed entity type is dynamic.
$needed_type = 'node';
if ($entity->getEntityTypeId() == $needed_type) {
}
Get Information of entity
// Get the ID.
$entity->id();
// Get the bundle.
$entity->bundle();
// Check if the entity is new.
$entity->isNew();
// Get the label of an entity. Replacement for entity_label().
$entity->label();
// Get the URL object for an entity.
$entity->toUrl();
// Get internal path, path alias if exists, for an entity.
$entity->toUrl()->toString();
// Create a duplicate that can be saved as a new entity.
$duplicate = $entity->createDuplicate();