15

I have created a custom module and created a yml file to create a menu

system.menu.custom_menu.yml

id: custom_menu
label: 'Custom menu'
description: 'Custom menu.'
langcode: en
locked: true
dependencies:
  - mymod

When I installed my module it creates the the custom menu. But then When I uninstall the module and try to install it again I get the following exception

exception 'Drupal\Core\Config\PreExistingConfigException' with message 'Configuration objects (system.menu.custom_menu) provided by mymod already exist in active configuration' in
/var/www/drupal8/core/lib/Drupal/Core/Config/PreExistingConfigException.php:70

What I am doing wrong? Is there any way to remove my configuration (system.menu.custom_menu) from the configurations when I uninstall my module?

2

1 Answer 1

46

The easiest way is to ensure that the config has a dependency on your module.

dependencies:
  module:
    - yourmodule
  enforced:
    module:
      - yourmodule

Then Drupal will automatically remove that configuration and also warn in the UI that it will be removed.

Note that this only works for new installations, it won't fix existing ones.

An alternative is to put the configuration in config/optional instead of config/install, then it will only be created if it doesn't exist yet and the dependencies are met.

7
  • 1
    I just observed on un-installing a module in d8, drupal cleans-up all the configuration. I had some configurations on config/install/module.settings.yml I installed the module, looked into config db table, I could see the configurations in the table, then I simply uninstalled the module re-check the config table and configurations are gone! Am I missing something here?
    – arpitr
    Commented Mar 2, 2016 at 12:18
  • Looks like this approach doesn't work with Entity Reference fields at the moment. I created a bug report: Config entities removed in wrong order causes PDOException
    – colan
    Commented Jul 7, 2016 at 16:44
  • 2
    Any explanation for the "enforced" bit? I mean, a dependency is a dependency. Isn't its enforcement a given? Is that's what's necessary for the uninstall? Commented Sep 4, 2016 at 23:20
  • Normal dependencies are calculated by code. Just becaouse you define a node type doesn't mean that anything specifically depends on your module. Saving a config entity re-calculates dependencies and your module will not be in that list.. unless you explicitly add it as an enforced dependency.
    – Berdir
    Commented Sep 5, 2016 at 0:09
  • "Note that this only works for new installations, it won't fix existing ones." - is there any manual SQL tweak that will fix this? I've tried DELETE FROM config WHERE ... and a drush cr after pm-uninstall but when I next en/pm-uninstall, the enforced: is still not respected. Is the dependency tree stored elsewhere?
    – J-P
    Commented Nov 29, 2016 at 10:43

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