2

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);
1
  • 1
    Can't test it at the moment but try $id_field = $entity->getKey('id');
    – Clive
    Jan 5, 2022 at 13:13

1 Answer 1

3

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

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.