1

I have entity that has bundles defined in code(hook_entity_bundle_info) and does not use config entity. It also defines fields for each bundle in \Drupal\Core\Entity\FieldableEntityInterface::bundleFieldDefinitions. But when I install the module the bundle fields are not created, only the base fields.

According to documentation this is possible and config entity is not needed to provide bundles and fields. So do I have to manually create the fields in hook_install or I'm missing something here?


If I run the following code only one field will be created out of 11. Strangely that field is my custom field that I've defined in the my module. Others(string, entity reference..) are left out.

  $entity_type_id = 'resource';
  $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
  $bundles = \Drupal::entityManager()->getBundleInfo($entity_type_id);
  $update_manager = \Drupal::entityDefinitionUpdateManager();

  foreach (array_keys($bundles) AS $bundle) {
    $fields =\Drupal\mymodule\Entity\Resource::bundleFieldDefinitions($entity_type, $bundle, []);
    if (!empty($fields)) {
      foreach ($fields AS $name => $definition) {
        $update_manager
          ->installFieldStorageDefinition($name, $entity_type_id, $entity_type->getProvider(), $definition);
      }
    }
  }

If I run the following code the fields are present, so it's not an issue with definition.

\Drupal::service('entity_field.manager')->getFieldDefinitions('my_type', 'my_bundle');

I found few references on the internet for hook_entity_field_storage_info but so far I have no idea what to do with it.

  • #191395 hints as to what to do but no usable info in there as well. – user21641 Oct 4 '16 at 8:31
0

This is not answer to the problem I had but a workable solution nonetheless. In the end I have created custom entity per each "bundle" that I have initially planned.

It actually resulted in less tables and also it provided option to handle logic that I have initially planned to do via plugins.

The only drawback of this solution are some route handlers where I have to provide the entity type via option parameter in order to be able to use single handler to get a page title, for example, due to the variable name "restriction" in route handlers.

Also in entity references or entity loader I have to use entity type only instead of entity type and bundle but that's totally fine.

I am using single entity base class, the same forms and so on so not that big of a deal(for now).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy