1

If I want to get an entity's bundle object, with a node, I can do something like:

$bundle_object = \Drupal::entityTypeManager()
  ->getStorage('node_type')
  ->load($node->bundle());

But this seems a little long-winded. Is there a way to get the object directly from an entity? Something like $entity->getBundleObject()?

3
  • 1
    I doubt you’ll find a generic method for this, not one on the core ContentEntityType anyway - bundles are optional so there isn’t always an object to provide
    – Clive
    Sep 3, 2021 at 13:37
  • @Clive is correct, if you wanted to shorten this you could create a new Storage Handler Sep 3, 2021 at 13:57
  • Ok, thanks folks. I didn't see one so I figured that was the case, but never really felt great about how I was labeling it.
    – sonfd
    Sep 3, 2021 at 14:01

1 Answer 1

2

The bundle field is a reference field and you can load the bundle object via the field property entity:

$node_type = $node->type->entity;

More generic for any content entity:

if ($entity->getEntityType()->hasKey('bundle')) {
  $bundle = $entity->get($entity->getEntityType()->getKey('bundle'))->entity;
}
3
  • Instead of calling $entity->getEntityType()->hasKey('bundle') and then $entity->getEntityType()->getKey('bundle'), the code can just call $entity->getEntityType()->getKey('bundle') which returns FALSE when the key doesn't exist, and the key name when that key exists.
    – apaderno
    Sep 3, 2021 at 19:38
  • 1
    Yes, the has method is not really necessary and could be removed. But a lot of people use them to make code easier to read.
    – 4uk4
    Sep 3, 2021 at 20:00
  • 1
    It makes clear, as @Clive commented, that bundles are optional. If the entity type has bundles, the bundle key has to be specified.
    – 4uk4
    Sep 3, 2021 at 20:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.