0

I have custom fields that I need to add to specific entity types and bundles with hook_entity_bundle_field_info(). However, I have to decide on which one to add depending on already existing fields, hence I need to ask for those. The hook function only receives the base field definitions passed as an argument, not the bundle fields. And, unfortunately, it seems I cannot use \Drupal::service('entity_field.manager')->getFieldDefinitions() from inside hook_entity_bundle_field_info() because it leads to an out-of-memory error, as it very probably calls itself repeatedly.

How can I make decisions depending on the presence and settings (eg. enabled status) of already existing fields?

2 Answers 2

0

To add a new field basing on the existing fields, the code needs to use hook_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle), which receives the list of the already defined fields (an array) to which new fields can be added, not hook_entity_bundle_field_info().

The Field module implements field_entity_bundle_field_info() because it does not need to add fields basing on the existing ones. It just adds its own fields, without checking which fields already exist.

1
  • 1
    Ooops, that was a stupid oversight. For some reason I assumed the alter hook will be called for each display, not just in the beginning to define. But it's info(), of course. It doesn't help as much as I hoped because Commerce adds these fields to the form display mode rather than the bundle itself, actually, as I found out in the meantime, but that doesn't change the general veracity of your answer. Thanks.
    – Gábor
    Commented Jun 23 at 14:02
0

I found the core field module to use a direct entity query approach like:

$ids = \Drupal::entityQuery('field_config')
  ->condition('id', $entity_type->id() . '.' . $bundle . '.', 'STARTS_WITH')
  ->execute();
$field_configs = FieldConfig::loadMultiple($ids);

It looks like the actual way forward.

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.