Skip to main content

Devbit

Get "key" from entity type

When working with entities dynamically, the base field name of a specific entity key (e.g., the primary ID field) is not always known beforehand. Given only the entity type ID, the entity key needs to be determined dynamically.
$entity_type_id = 'node';
$definition = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
$id_key = $definition->getKey('id');

Issue:

When working with entities dynamically, the base field name of a specific entity key (e.g., the primary ID field) is not always known beforehand. Given only the entity type ID, the entity key needs to be determined dynamically.

Solution:

Load all base field definitions of the given entity type via entityTypeManager() and return the ID with the method getKey().

Profilfoto Mathias Grab

Mathias Grab

Trainee Webentwicklung

Test

Ihre Drupal-Website zukunftssicher machen

Wir prüfen Ihr System und zeigen, was Sie für AI, Wartung und Upgrades brauchen.