If I have an entity type id as a string, how I can tell which base fields are defined for that entity type?
For example, how do I programatically check that an entity type has the "changed" field?
If I have an entity type id as a string, how I can tell which base fields are defined for that entity type?
For example, how do I programatically check that an entity type has the "changed" field?
How to get the base fields for an entity type id:
$base_fields = \Drupal::entityManager()->getBaseFieldDefinitions($entity_type_id);
You get an array. The keys are the field names. Example how to loop through this array:
foreach ( $base_fields as $field_name => $definition ) {
echo "$field_name: ", $definition->getDescription(), "\n";
}
Edit:
The method has moved to the service EntityFieldManager
:
$base_fields = \Drupal::service('entity_field.manager')
->getBaseFieldDefinitions($entity_type_id);
The easiest way is through the entity type manager service, by getting the entity type definition and class:
$entity_type = 'node';
$container = \Drupal::getContainer();
/** @var \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager */
$entity_type_manager = $container->get('entity_type.manager');
$entity_type_definition = $entity_type_manager->getDefinition($entity_type);
$entity_type_class = $entity_type_definition->getClass();
$fields = call_user_func([$entity_type_class, 'baseFieldDefinitions'], $entity_type_definition);
if (!empty($fields['changed'])) {
// Do something.
}
\Drupal->entityTypeManager()
If you know the class of the entity type then:
$fields = Foo::baseFieldDefinitions(\Drupal::entityTypeManager()->getDefinition('foo'));
Here's an example for drush
, sample $entity_type_id
is user
but could be node
etc..
drush ev 'var_export(array_keys(\Drupal::service("entity_field.manager")->getBaseFieldDefinitions("user")))'