Score:2

Programmatically find out field name of an Id-field

cn flag

Depending on the type of entity, it is either nid/vid/uid and possibly other. It is nice to have an ->id() method which allows you to work with data in an uniform fashion without relying on those details, but there are quite some use-cases, where I am running into troubles.

Just an example, getting list of revision ids for an generic entity seems not possible without knowing the name of the id-field.

$entityTypeId = $entity->getEntityTypeId();
$entityId = $entity->id();

$typeStorage = \Drupal::entityTypeManager()->getStorage($entityTypeId);

$query = $typeStorage->getQuery();
$query->allRevisions();
$query->condition("??????", $entityId);
cn flag
Can't test it at the moment but try `$id_field = $entity->getKey('id');`
Score:3
in flag

EntityType provides a function to get field keys: EntityType::getKeys. The result is an array and the id key identifies the property name of the primary field.

See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityType.php/function/EntityType%3A%3AgetKeys

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.