3

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.

Drupal\Core\Field\FieldException: Attempt to create a field field_example that does not exist on entity type node. in Drupal\field\Entity\FieldConfig->getFieldStorageDefinition() (line 312 of core\modules\field\src\Entity\FieldConfig.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 \Drupal\field\Entity\FieldStorageConfig;

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!

1
  • 2
    Normally managing the fields just works by installing and uninstalling the module. Try this on a copy of the database until it works without problems. The error messages are caused by a field only partially installed. – 4k4 Oct 19 '20 at 6:26
5

To properly manage fields added by a module, so that a field is added and removed when the module is installed and uninstalled, add an enforced dependency for your own module to the yaml file:

/config/install/field.storage.node.field_example.yml

...
dependencies:
  enforced:
    module:
      - mymodule

See https://www.drupal.org/node/2404447

Your Answer

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

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