Score:0

Entity agnostic way of retrieving title

mw flag

Is there a way of the Title/Label/Name of an unknown entity type via 1 method?

At the moment if it's a node, I have to use $entity->getTitle(), for a user it's $entity->getAccountName(), for a taxonomy term it'd be $entity->getName()

In my head they all feel like the same piece of information, is there a way of retrieving it without having to write out possibilities for each type of entity?

Jaypan avatar
de flag
You use `$entity->label()`.
Andrew Morris avatar
mw flag
Perfect! I knew there must be a way of doing it
Score:2
cn flag

All entity types, content and config both, have a label() method (see EntityInterface::label()).

$label = $entity->label();

You can use this reliably on any entity. The entity classes themselves (Node, Term, etc) define the most appropriate value, so for nodes you get the title field, for terms you get the name field, and so on.

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.