entities – How to properly manage field types for a content type created by a module for Drupal 9?


I’m a bit confused about two different errors I get, which seem to contradict each other. I guess I didn’t register my field types properly. The first one appears when I try to uninstall my module.

DrupalCoreFieldFieldException: Attempt to create a field field_example that does not exist on entity type node. in DrupalfieldEntityFieldConfig->getFieldStorageDefinition() (line 312 of coremodulesfieldsrcEntityFieldConfig.php).

The second one appears as an error message within the UI when I try to fix it by introducing another module which should only create the field type.

Unable to install Helper, field.field.node.content_type_example.field_example already exists in active configuration.

In general, the module calls an external API and fetches data which is then used to create nodes with several fields. These are defined inside the config/install directory. Furthermore, inside src/Plugin/Field there are FieldType, FieldFormatter and FieldWidget classes, more or less as described here.

I used this module when I tried to fix the first error without a helper module. With its help, I removed the field types created by my module in the first place. Unfortunately, I don’t know a lot about drush, which seems to be capable of solving the issue. On the other hand, it would be great if it was possible to “reset” the content type and the field types programmatically whenever the module is installed or uninstalled. So far, I tried the following code, without much luck:

<?php
// mymodule.install file
use DrupalfieldEntityFieldStorageConfig;

function mymodule_install() {
  if (FieldStorageConfig::loadByName('node', 'field_example')) {
    FieldStorageConfig::loadByName('node', 'field_example')->delete();
  }
}

Does someone know how I can fix the error and how I should manage these fields in the future? Thanks!