Get Human-Readable Name Of Media Bundle In Drupal 8

PROBLEM
I need to get the label/name of the bundle of a media entity for a preprocess. Unfortunately, the following code to get the label of the bundle does not work for media:

$current_entity->type->entity->label()

I’ve tried to google various things but nothing came up that was helpful. The code $current_entity->bundle() works to get the machine name of the bundle; but how can we get the human-readable name of the bundle?

SOLUTION
The solution requires something really stupid. If anyone has a method I can call instead, more than welcome to comment!

\Drupal\media\Entity\MediaType::load($current_entity->bundle())->label()

That’s really stupid!

By the way, just to remember, how to get the entity type you can use:

$current_entity->getEntityTypeId()

I think this ticket could possibly make the solution easier: https://www.drupal.org/project/drupal/issues/969180. All entities should use the same methods to get the type, bundle, label, etc. Also, label shouldn’t be ambiguous. It should either be for the title of the entity or for what the entity actually is.

Leave a Reply

Your email address will not be published. Required fields are marked *