Score:1

How can I load an entity's bundle object from a loaded entity?

in flag

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()?

cn flag
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
cn flag
@Clive is correct, if you wanted to shorten this you could create a new [Storage Handler](https://chromatichq.com/insights/creating-and-using-entity-storage-methods)
sonfd avatar
in flag
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.
Score:1
cn flag

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;
}
apaderno avatar
us flag
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.
4uk4 avatar
cn flag
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 avatar
cn flag
It makes clear, as @Clive commented, that bundles are optional. If the entity type has bundles, the bundle key has to be specified.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.