2

Given an $entityTypeId as string, how can I determine if this entity type is fieldable? That is, if entities of that type implement FieldableEntityInterface?

1

2 Answers 2

4

There might be a simpler way but I think this should be pretty reliable:

// Inject the entity_type.manager service instead if possible.
$class = \Drupal::entityTypeManager()
    ->getDefinition($entity_type_id)
    ->getOriginalClass();

$interface = 'Drupal\Core\Entity\FieldableEntityInterface';

if (in_array($interface, class_implements($class))) {
    ...
}
8
  • 2
    Nice! Maybe is_a($class, $interface, TRUE) would be faster than in_array()?
    – donquixote
    Aug 13, 2017 at 20:31
  • @donquixote Forgot that function even existed! Yeah it'd almost definitely be a bit faster to use is_a. Probably nothing earth shattering though
    – Clive
    Aug 13, 2017 at 20:36
  • 3
    And even easier is to use the predefined method entityClassImplements() on the entity_type definition object, ->getDefinition()->entityClassImplements(FieldableEntityInterface::class)
    – Berdir
    Aug 14, 2017 at 6:07
  • 1
    I would clarify first what fieldable stands for. In Drupal 7 terminology entity type becomes fieldable if it has "fieldable" key in its definition. Which means it accepts fields being attached to it. From this point the answer is not correct because in Drupal 8 all content entities implement FieldableEntityInterface but not all of them are truly fieldable. You can check for field_ui route to find out if it is possible to attach fields to a given entity type $entity_type_definition->get('field_ui_base_route').
    – ya.teck
    Aug 14, 2017 at 10:08
  • 2
    @ya.teck it is quite correct, actually. That flag no longer exists. any content entity consists of fields. To be extra correct, you could check whether the storage implements api.drupal.org/api/drupal/…, but all content entities using the standard storage do. The field_ui flag key, as the name implies, only defines if and where field_ui should expose the UI. But even without UI, configurable fields will work as long as the storage implements it
    – Berdir
    Aug 14, 2017 at 20:01
0

This might be a bit simpler:

if (method_exists(\Drupal::entityTypeManager()->getDefinition($entity_type_id)->getOriginalClass(), 'hasField')) {
...
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.