Generic way to get a Entity's bundle label

Last updated on 27/06/2019

A helper function to get the entity's( Taxonomy Term, Node, ... ) bundle label if available.

 

use Drupal\Core\Entity\ContentEntityInterface;
 
/**
 * Helper function to get the Entity's bundle label if available.
 *
 * @param \Drupal\Core\Entity\ContentEntityInterface $entity
 *   The Entity object.
 *
 * @return string|null
 *   The Entity's bundle or NULL if not available.
 */
function getEntityBundleLabel(ContentEntityInterface $entity) {
 
  try {
    $bundleTypeId = $entity->getEntityType()->getBundleEntityType();
    $bundleLabel = \Drupal::entityTypeManager()
      ->getStorage($bundleTypeId)
      ->load($entity->bundle())
      ->label();
    return $bundleLabel;
  }
  catch (\Exception $e) {
    watchdog_exception('entity_bundle_label_get', $e);
  }
 
}